Valentin Coudert Valentin Coudert - 1 year ago 174
Python Question

Blueprint's before_request not called (Flask)

I'm working on someone's else code and cannot find how to make the

before_request
function called.

Am I doing anything wrong ?

In
main.py
I have

from server.api.line.blueprint import line_api_blueprint
from server.api.stopping_point.blueprint import stopping_point_blueprint

app = Flask(__name__)
app.register_blueprint(line_api_blueprint, url_prefix=u"/api/line")
app.register_blueprint(stopping_point_blueprint, url_prefix=u"/api/stopping_point")

@line_api_blueprint.before_request
@stopping_point_blueprint.before_request
def check_if_connected():
print "\n\n\n LOOOOOOL \n\n\n" # never printed


In
line/blueprint.py


line_api_blueprint = Blueprint(u'line_api', __name__)

line_api = Factory().build(u"LineApi")


@line_api_blueprint.route(u'/', methods=[u"GET"])
def line():
if request.method == u"GET":
return jsonify({
u"items": line_api.list()
}), 200


[edit]

It works well if I move the
before_request
handler to the blueprint file. So I guess it has something to do with the import but when I print
section_api_blueprint
, it says it's a correct blueprint object.

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