简体   繁体   中英

AttributeError on current_user.is_authenticated()

I'm using Flask-Login and I want to check if a user is logged-in by calling current_user.is_authenticated().

My Flask application is organized into Blueprints with a main __init__.py file that sets up my app, sets up Blueprints, and initializes Flask-Login. I have a script, run.py , located up one directory from __init__.py that instantiates the application and runs it if in debug mode.

__init.py__ looks (in part) like this:

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

When I run this, from run.py (which looks, in part, like this):

from panel import app 

app.run(host='0.0.0.0', debug=True)

This Exception is raised:

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'

Because I omitted some lines for brevity, the line numbers in that traceback do not match the code I posted, but you can see that the line logging.warning(current_user.is_authenticated()) seems to be where the error occurs.

Any help is appreciated.

You can't call

current_user.is_authenticated()

outside of a method/view, because the code outside of the methods/views will be run outside of a request.

If you're not in a request, there is no current_user on which to check authentication.

May be you can try

login_manager.init_app(app)

Flask-Login

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM