Valentin Coudert Valentin Coudert - 1 year ago 112
Python Question

Flask doesn't call blueprint's before_request function

I want to add a

before_request
function to a blueprint. After registering the blueprint on the app, I decorate a function with
before_request
. However, the function is never called. Why doesn't it work?

__init__.py
:

app = Flask(__name__)

from server.api import api
app.register_blueprint(api, url_prefix='/api')

@api.before_request
def check_if_connected():
assert False, 'this is never printed'


api/__init__.py
:

api = Blueprint('api', __name__)

Answer Source

Flask doesn't see what happens to the blueprint after it is registered. All setup, such as registering before request functions, must happen before registering the blueprint. Typically, things are registered near the blueprint's definition or in it's package, not after a semantically unrelated import.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download