AttributeError: '_AppCtxGlobals' object has no attribute 'user' in Flask

前端 未结 1 1787
遥遥无期
遥遥无期 2021-02-05 06:22

I\'m trying to learn flask by following the Flask Mega Tutorial. In part 5, the login() view is edit like so:

@app.route(\'/login\', methods = [\'GET\', \'POST\'         


        
相关标签:
1条回答
  • 2021-02-05 06:58

    The same tutorial, a little further on, explains how g.user is set:

    The g.user global

    If you were paying attention, you will remember that in the login view function we check g.user to determine if a user is already logged in. To implement this we will use the before_request event from Flask. Any functions that are decorated with before_request will run before the view function each time a request is received. So this is the right place to setup our g.user variable (file app/views.py):

    @app.before_request
    def before_request():
        g.user = current_user
    

    This is all it takes. The current_user global is set by Flask-Login, so we just put a copy in the g object to have better access to it. With this, all requests will have access to the logged in user, even inside templates.

    Your code is apparently missing this before_request handler.

    0 讨论(0)
提交回复
热议问题