Where I put my project before_request

So, I have pre-routing for my user module. But now I want to access g.users from other drawings. I found the only way to do this is to copy the code below into each individual project.

I tried putting it in my app.py for @ app.before_request, but then you have errors because you need to import the session, g, User, and then you still get _requestglobal errors in other places.

@app.before_request def before_request(): g.user = None if 'user_id' in session: g.user = User.query.get(session['user_id']); 

What is the best place to place it?

I get a lot:

 AttributeError: '_RequestGlobals' object has no attribute 'user' 
+7
source share
4 answers

I think you are doing it well, trying to initialize the user in before_request , the problem is that the g object has nothing before the request, so you need to deal with it differently. Most likely, the user can use cookies in before_request , and then add it to the session, from there, possibly to g . I think it's worth taking a look at Flask-login or using it. Or just read the code and maybe it will give you some ideas.

+3
source

A bit late, but:
This is what I do:
Use Blueprint variable to set before request

 myblueprint = Blueprint('myblueprint', __name__, template_folder="templates") def before_myblueprint(): #code here myblueprint.before_request(before_myblueprint) 
+13
source

Buleprint.before_request is called before each request within the project. If you want to name it before all drawings, use before_app_request .

+8
source

I'm even later here, but by increasing Johnston's answer, you can use the same before_request decoder, for example:

 bp_v1 = Blueprint('api_v1', __name__) @bp_v1.before_request def before_anything(): pass 
+1
source

All Articles