我正在使用 Flask-Login,我想通过调用 current_user.is_authenticated() 来检查用户是否已登录。
我的 Flask 应用程序被组织成蓝图,其中包含一个主__init__.py
文件,用于设置我的应用程序、设置蓝图和初始化 Flask-Login。我有一个脚本,run.py
位于一个目录中,__init__.py
它实例化应用程序并在调试模式下运行它。
__init.py__
看起来(部分)像这样:
from flask import Flask, session, request, render_template
from flask.ext.login import LoginManager, current_user
from panel.views import dash, projects
from panel.users.models import User, AnonymousUser
app = Flask(__name__)
app.config.from_object("configure")
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = "/signin"
login_manager.anonymous_user = AnonymousUser
@login_manager.user_loader
def load_user(str_id):
return User.user_loader(str_id)
# Register all blueprints here.
app.register_blueprint(dash.bp, url_prefix="/dash")
app.register_blueprint(projects.bp, url_prefix="/projects")
logging.warning(current_user.is_authenticated())
当我运行它时,从run.py
(部分看起来像这样):
from panel import app
app.run(host='0.0.0.0', debug=True)
引发此异常:
Traceback (most recent call last):
File "run.py", line 5, in <module>
from panel import app
File "/opt/www/panel/panel/__init__.py", line 40, in <module>
logging.warning(current_user.is_authenticated())
File "/opt/virtualenvs/coefficient/lib/python2.6/site-packages/werkzeug/local.py", line 336, in __getattr__
return getattr(self._get_current_object(), name)
File "/opt/virtualenvs/coefficient/lib/python2.6/site-packages/werkzeug/local.py", line 295, in _get_current_object
return self.__local()
File "/opt/virtualenvs/coefficient/lib/python2.6/site-packages/flask_login.py", line 403, in <lambda>
current_user = LocalProxy(lambda: _request_ctx_stack.top.user)
AttributeError: 'NoneType' object has no attribute 'user'
因为为简洁起见我省略了一些行,所以该回溯中的行号与我发布的代码不匹配,但您可以看到该行logging.warning(current_user.is_authenticated())
似乎是发生错误的地方。
任何帮助表示赞赏。