Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: How to run a method before every route in a blueprint?

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?

like image 556
user606006 Avatar asked Dec 16 '15 03:12

user606006


People also ask

How do you use before request in Flask?

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.

How do you run a Flask in blueprints?

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.

How do you pass parameters on a Flask route?

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.

What is the default route request in Flask?

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.


2 Answers

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

like image 182
Matt Healy Avatar answered Oct 19 '22 18:10

Matt Healy


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.

like image 41
Miguel Avatar answered Oct 19 '22 19:10

Miguel