Flask: How to run a method before each route in a project?

I want my Flask Blueprint to always run the method before executing any routes. Instead of decorating every route method in my project with a special decorator, I want to be able to do something like this:

def my_method(): do_stuff section = Blueprint('section', __name__) # Register my_method() as a setup method that runs before all routes section.custom_setup_method(my_method()) @section.route('/two') def route_one(): do_stuff @section.route('/one') def route_two(): do_stuff 

Then basically both /section/one and /section/two will run my_method() before executing the code in route_one() or route_two() .

Is there any way to do this?

+5
source share
2 answers

You can use the before_request decorator for drawings. Like this:

 @section.before_request def my_method(): do_stuff 

This automatically registers the function that should be executed before any routes related to the drawing.

+10
source

You can use before_request for this:

 @section.before_request def before_request(): do_stuff 

http://flask.pocoo.org/docs/0.10/api/#flask.Flask.before_request

0
source

Source: https://habr.com/ru/post/1238329/


All Articles