Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create Flask before_request view for specific views?

I'm building a system using Flask which contains both a website and an api for an app. I've got a before_request defined for the webviews as follows:

@app.before_request
def before_request():
    g.user = current_user
    # And I do some more stuff here..

I've got my views in a folder based structure like this:

views (folder)
---------------
  - __init__.py
  - apiviews.py
  - webviews.py

Because I'm using a token based login system for the api I now want to define a different before_request for all the apiviews. Is there a way that I can do this? Maybe I need to define a decorator or something? All tips are welcome!

like image 293
kramer65 Avatar asked Sep 03 '25 08:09

kramer65


1 Answers

You cannot use a before_request hook for specific views, not in the same app.

Your options are to:

  • Use a separate Blueprint for your API and website; you can register a before_request per blueprint and it'll be applied to the views for that blueprint only.
  • Use per-view decorators rather than before_request.
  • filter on the request path in the before_request handler; if request.path.startswith(...) style testing.
like image 132
Martijn Pieters Avatar answered Sep 04 '25 21:09

Martijn Pieters