Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put my blueprint before_request

Tags:

python

flask

So I have the before request routing for my user module. But now I want to access g.users from other blueprints as well. I found the only way to do it, is to copy the code below to every single blueprint.

I tried putting it in my app.py for @app.before_request, but then you have errors because you have to import session, g, User, and then still you 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's the best place to put it?

I get a lot of:

AttributeError: '_RequestGlobals' object has no attribute 'user'
like image 819
Dexter Avatar asked Dec 01 '12 08:12

Dexter


People also ask

How to add Blueprint in Flask?

To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() . When a Flask Blueprint is registered, the application is extended with its contents. While the application is running, go to http://localhost:5000 using your web browser.

Why use Blueprints in Flask?

Now, this is where Flask Blueprints come into picture. Blueprints help you structure your application by organizing the logic into subdirectories. In addition to that, you can store your templates and static files along with the logic in the same subdirectory. Now you can see that you have clear separation of concerns.


2 Answers

Blueprint.before_request is called before each request within the blueprint. If you want to call it before all blueprints, please use before_app_request.

like image 164
imwilsonxu Avatar answered Sep 23 '22 09:09

imwilsonxu


A little late here but:
This is what I do:
Use the Blueprint variable to set the before request

myblueprint = Blueprint('myblueprint', __name__, template_folder="templates")

def before_myblueprint():
    #code here

myblueprint.before_request(before_myblueprint)
like image 37
Johnston Avatar answered Sep 20 '22 09:09

Johnston