如何在烧瓶中只执行一次代码块?

ram*_*amu 4 python flask

我想登录,谁登录使用FLASK的应用程序.我尝试使用, @app.before_request但问题是我需要访问通过烧瓶全局变量的用户名,如果我使用这个装饰器我得不到.

此外,使用如下的全局变量也不起作用.如何在请求上下文中获取全局变量?

import logging
import time
from flask import request, flash
from flask import g
from forms import QueryForm, RequestForm, Approve_Reject_Btn_Form
from query.sqlQuery import SQLQuery
from database.oracle import Database
import datetime
from requests import Session

logger = logging.getLogger(__name__)
login_count = 0
'''
Homepage route - Displays all the tables in the homepage
'''
@app.route('/')
@app.route('/index')
def index():
  try:
    if not g.identity.is_authenticated():
      return render_template('homepage.html')
    else:
      try:
        global login_count
        if login_count == 0:
          username = g.identity.name
          user_ip = request.headers.get('IP_header')
          current_time = time.strftime('%c')
          db = Database(db_config.username, db_config.password)
          query = "INSERT INTO UserIP (username, login_time, ip_address) values ('%s', systimestamp, '%s')" % (username, user_ip)
          dml_query(query)
          logger.debug('User : %s, ip : %s, noted at time : %s, login_count : %s', username , user_ip, current_time, login_count)
          login_count = 1
Run Code Online (Sandbox Code Playgroud)

Bor*_*ris 10

至于你的问题"如何在烧瓶中只执行一次代码块?" 去,这样的事情应该工作正常:

app = Flask(__name__)

@app.before_first_request
def do_something_only_once():
    app.logger.setLevel(logging.INFO)
    app.logger.info("Initialized Flask logger handler")
Run Code Online (Sandbox Code Playgroud)

问题的第二部分是如何设置全局变量,例如示例中的登录计数器.对于这样的事情,我建议你使用外部缓存.请参阅下面的示例,其中包含werkzeug SimpleCache类.在生产中,您应该使用redis或mongodb替换SimpleCache.

from werkzeug.contrib.cache import SimpleCache

class Cache(object):
    cache = SimpleCache(threshold = 1000, default_timeout = 3600)

    @classmethod
    def get(cls, key = None):
        return cls.cache.get(key)
    @classmethod
    def delete(cls, key = None):
        return cls.cache.delete(key)
    @classmethod
    def set(cls, key = None, value = None, timeout = 0):
        if timeout:
            return cls.cache.set(key, value, timeout = timeout)
        else:    
            return cls.cache.set(key, value)
    @classmethod
    def clear(cls):
        return cls.cache.clear()
Run Code Online (Sandbox Code Playgroud)

您可以像这样使用Cache类.

from mycache import Cache

@app.route('/')
@app.route('/index')
def index():
    if not g.identity.is_authenticated():
        return render_template('homepage.html')
    else:
        login_count = Cache.get("login_count")
        if login_count == 0:
            # ...
            # Your code
            login_count += 1
            Cache.set("login_count", login_count)
Run Code Online (Sandbox Code Playgroud)

编辑1:添加了after_request示例

Per Flask文档中,after_request decorator用于在每次请求后运行注册函数.它可用于使缓存无效,更改响应对象,或几乎任何需要特定响应修改的内容.

@app.after_request
def after_request_callback(response):
    # Do something with the response (invalidate cache, alter response object, etc)
    return response
Run Code Online (Sandbox Code Playgroud)