Python Flask-Login 检查用户是否在没有装饰器的情况下通过身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20419228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:23:25  来源:igfitidea点击:

Flask-Login check if user is authenticated without decorator

pythonflaskflask-login

提问by Ospho

From the Flask-Login docs, it's described how a user of the system can require an authenticated User-model to access a method utilising the decorator syntax:

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

from flask_login import login_required    

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

Now thats all well and good, but I want to be able to examine if the user is logged in a method, something like this:

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

@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
    ...

The reason for this, is because it factorises the GET and POST requests rather than duplicating routes for authenticated users and unauthenticated users.
How can I do this? Is it possible?

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

采纳答案by codeape

This is very simple in flask:

这在烧瓶中非常简单:

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")

See the documentation on anonymous users.

请参阅有关匿名用户的文档

回答by flyer

You could refer to the example here.

你可以参考这里的例子。

When the user has logged in, set session['logged_in']=True. At the same time, you can use Flask-login API to do some configurations in case that you want to use its functionality.
When you want to check whether the user has logged in manually rather than use the Flask-login API, then check the value of session['logged_in'].

用户登录后,设置session['logged_in']=True. 同时,如果你想使用它的功能,你可以使用 Flask-login API 做一些配置。
当您想检查用户是否已手动登录而不是使用 Flask-login API 时,请检查session['logged_in'].