简体   繁体   中英

Strange Flask Blueprint behaviour

I have this code (working):

bp = Blueprint(...)

@bp.before_request
def before_request():
     if self.auth_callback is not None:
         return self.auth_callback()

 self.app.register_blueprint(
     bp,
     url_prefix=self.config.get("FILE_UPLOAD_PREFIX")
 )

And this is not working:

bp = Blueprint(...)

self.app.register_blueprint(
    bp,
    url_prefix=self.config.get("FILE_UPLOAD_PREFIX")
)

 @bp.before_request
 def before_request():
     if self.auth_callback is not None:
         return self.auth_callback()

Can someone explain me, whats happening here plz? Why is the order important?

The reason is that the Flask app won't use the given Blueprint object directly, but save its state in the app at registration with the help of the BlueprintSetupState class. If you modify the Blueprint object after it is registered, it will have no effect on the previously saved state.

See the BlueprintSetupState class in the Flask sources for more details, where its class documentation states the following:

Temporary holder object for registering a blueprint with the application. An instance of this class is created by the :meth: ~flask.Blueprint.make_setup_state method and later passed to all register callback functions.

EDIT : My previous answer was a little misleading, because the callbacks are not saved in the BlueprintSetupState instance, but in the App instance. For example, when you give a function to run before each request with before_request , the given function will be added to the before_request_funcs list of the app instance at registration . This is why it has no effect to change the callback after registration. See the register and before_request methods of the Blueprint class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM