这很可能是一个愚蠢的问题,但我仍然找不到答案。
Documentation对于 Flask-Security 说:
If there are only certain times you need to require that your user is logged in, you can do so with:
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
但它没有给出这个“current_user”变量从何而来的线索。当我尝试在我的应用程序源代码中使用它时,我收到“NameError: global name 'current_user' is not defined”毫不奇怪。
奇怪的是,当我在我的 HTML 模板中使用变量时,render_template 函数以某种方式完成而没有错误。
所以,问题是,我如何在我的应用程序中使用“current_user”变量,如果我的应用程序不使用,模板引擎如何“知道”它?
请您参考如下方法:
您需要import current_user .
from flask_login import current_user
就它的来源而言 - 它来自不同的包,flask-login :
#: A proxy for the current user. If no user is logged in, this will be an
#: anonymous user
current_user = LocalProxy(lambda: _get_user())
