如何在整个应用程序中重复检查 Flask 中的会话变量?

How do I check for a session variable in flask repeatedly across the application?

我正在寻找一种有效的方法来检查每个视图的会话变量。我可以像下面的文档那样做,但是是否有一个全局函数或装饰器可以提取 username 而无需重复相同的行?

@app.route('/')
def index():
    if 'username' in session:   # this is repeated in every view
        username = session['username'] # this is repeated in every view
    return 'You are not logged in'

你猜对了。装饰器是一种审查会话并对结果做出反应的方法。在下面的示例中,如果用户未登录,则根据装饰器将用户重定向到适当的路由。如果用户名存储在会话中,则调用装饰路由。

如果登录对于相应的路由是可选的,则它是 public 并且不需要装饰器。但可能需要询问用户是否已登录。

from flask import (
    redirect,
    session,
    url_for
)
from functools import wraps

# ...

def is_authenticated():
    username = session.get('username')
    return username and len(username.strip()) > 0

def login_required(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if not is_authenticated():
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return wrapper

# Add the state query function to the jinja context.
app.jinja_env.globals.update(is_authenticated=is_authenticated)

@app.route('/login', methods=['GET', 'POST'])
def login():
    # your login code here!

@app.route('/secret')
@login_required
def secret():
    return 'You are logged in.'

@app.route('/public')
def public():
    if is_authenticated():
        return 'User is authenticated'
    return 'User is not authenticated'

此代码用于在模板中检查用户是否已登录。

    {% if is_authenticated() %}
      User is authenticated.
    {% else %}
      User is not authenticated.
    {% endif %}

如果你真的想在每个路由之前请求会话变量,before_request decorator might be a solution. In this case you cannot avoid storing variables in the g object 在你的路由中使用它们。但是,这超出了您的示例范围或不必要地使代码复杂化,因为它只需要使用额外的数据。
我认为我给出的代码对于简单的目的应该足够了。 对于更复杂的环境,我建议您查看 Flask-Login or Flask-Security.