How to use global in g.user flask

As far as I understand the g variable in Flask, it should provide me with a global place to store data, such as saving the current user after logging in. Is it correct?

I would like my navigation to display my username after logging in through the site.

My views contain

from Flask import g #among other things 

At login, I assign

 user = User.query.filter_by(username = form.username.data).first() if validate(user): session['logged_in'] = True g.user = user 

It seems I can not access g.user. Instead, when my base.html template has the following ...

 <ul class="nav"> {% if session['logged_in'] %} <li class="inactive">logged in as {{ g.user.username }}</li> {% endif %} </ul> 

I get an error message:

 jinja2.exceptions.UndefinedError UndefinedError: 'flask.ctx._RequestGlobals object' has no attribute 'user' 

Otherwise, the login works fine. What am I missing?

+48
python flask jinja2 flask-login
Nov 29 '12 at 1:12
source share
3 answers

g is a local thread and is for each request (see Note on proxies ), session also a local thread, but in the default context a cookie with a MAC address is saved and sent to the client.

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

The simplest thing (note simple != secure - if you need to take a safe look at Flask-Login ), just add the user ID to the session and load the user for 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 
+64
Nov 29 '12 at 17:40
source share
— -
+10
Oct 08 '15 at 3:20
source share

I would try to get rid of global combinations, think of my applications as a set of functions that perform tasks, each function has inputs and outputs and should not concern global ones. Just bring your user and pass it on, it will make your code much more verifiable. Even better: get rid of the flask; the flask is promoted using globals such as

 from flask import request 
-8
Feb 10 '16 at 15:11
source share



All Articles