Flask-Login检查用户是否在没有装饰器的情况下进行了身份验证

时间:2013-12-06 08:22:31

标签: python flask flask-login

在Flask-Login文档中,它描述了系统用户如何能够使用经过身份验证的用户模型来访问使用装饰器语法的方法:

from flask_login import login_required    

@app.route("/settings")
@login_required
def settings():
    pass

现在这一切都很好,但我希望能够检查用户是否登录了一个方法,如下所示:

@app.route('/main/', methods=['GET', 'POST'])
main_route():
    if request.method == 'GET':
         if user_is_authenticated():    #Do the authentication here
             #load authenticated /main/ html template etc.
             pass
         else:
             #load unauthenticated /main/ html template etc.
             pass
    ...

之所以这样,是因为它将GET和POST请求分解,而不是为经过身份验证的用户和未经身份验证的用户复制路由。
我怎样才能做到这一点?有可能吗?

2 个答案:

答案 0 :(得分:43)

烧瓶非常简单:

from flask_login import current_user

@app.route(...)
def main_route():
    if current_user.is_authenticated:
         return render_template("main_for_user.html")
    else:
         return render_template("main_for_anonymous.html")

the documentation on anonymous users

答案 1 :(得分:1)

您可以参考示例here

用户登录后,设置session['logged_in']=True。同时,如果要使用其功能,可以使用Flask-login API进行一些配置 如果要检查用户是否已手动登录而不是使用Flask-login API,请检查session['logged_in']的值。

相关问题