I want to make my Flask Blueprint always run a method before executing any routes. Instead of decorating every route method in my blueprint with a custom 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 code in route_one()
or route_two()
.
Is there a way to do this?
To run your code before each Flask request, you can assign a function to the before_request() method, this can be done using decorators to make it a little simpler. This function will run before each and every endpoint you have in your application.
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.
flask route params Parameters can be used when creating routes. A parameter can be a string (text) like this: /product/cookie . So you can pass parameters to your Flask route, can you pass numbers? The example here creates the route /sale/<transaction_id> , where transaction_id is a number.
By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods. If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC.
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
You can use the before_request decorator for blueprints. Like this:
@section.before_request
def my_method():
do_stuff
This automatically registers the function to run before any routes that belong to the blueprint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With