How to use g.user global in flask

后端 未结 3 2006
心在旅途
心在旅途 2020-12-02 07:48

As I understand the g variable in Flask, it should provide me with a global place to stash data like holding the current user after login. Is this correct?

I would

相关标签:
3条回答
  • 2020-12-02 08:09

    g is a thread local and is per-request (See A Note On Proxies). The session is also a thread local, but in the default context is persisted to a MAC-signed cookie and sent to the client.

    The problem that you are running into is that session is rebuilt on each request (since it is sent to the client and the client sends it back to us), while data set on g is only available for the lifetime of this request.

    The simplest thing to do (note simple != secure - if you need secure take a look at Flask-Login) is to simply add the user's ID to the session and load the user on each request:

    @app.before_request
    def load_user():
        if session["user_id"]:
            user = User.query.filter_by(username=session["user_id"]).first()
        else:
            user = {"name": "Guest"}  # Make it better, use an anonymous User instead
    
        g.user = user
    
    0 讨论(0)
  • 2020-12-02 08:10

    Minor correction, the g object is bound to the application context now instead of the request context.

    "Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request."

    0 讨论(0)
  • 2020-12-02 08:13

    I would try to get rid of globals all together, think of your applications as a set of functions that perform tasks, each function has inputs and outputs, and should not touch globals. Just fetch your user and pass it around, it makes your code much more testable. Better yet: get rid of flask, flask promotes using globals such as

    from flask import request
    
    0 讨论(0)
提交回复
热议问题