How to use g.user global in Python Flask?

Sometimes, we want to use g.user global in Python Flask.

In this article, we’ll look at how to use g.user global in Python Flask.

How to use g.user global in Python Flask?

To use g.user global in Python Flask, we can set g.user to the current user’s data before a request is made in an authenticated route.

For instance, we write

@app.before_request
def load_user():
    if session["user_id"]:
        user = User.query.filter_by(username=session["user_id"]).first()
    else:
        user = {"name": "Guest"}
    g.user = user

to add a load_user function that’s called before each request.

We use the @app.before_request to make load_user run before each request.

In it, we get the user’s data from the user_id key in the session object.

And then we assign that to g.user.

Now g.user should have the current user data in our views.

Conclusion

To use g.user global in Python Flask, we can set g.user to the current user’s data before a request is made in an authenticated route.