Reputation: 6307
I'm just interested how Flask's blueprints gets imported. It still imports the python module at the end of all the stuff done by Flask and if I'm right python does two things when importing: registers the module name in the namespace and then initialize it if needed.
So if Flask blueprint is initialized when it gets registered, so all the module then is in memory and if there are lots of blueprints to register, the memory just gets wasted, because in one request basically you use one blueprint. Not a big loss but still...
But if it is only registered in the namespace and initialized only when needed (when the real request reaches it), then it make sense to register them all at once (as is the recommended way I understood). This is I guess the case here :) But just wanted to ask and understand a bit deeper.
Upvotes: 3
Views: 574
Reputation: 3295
I'm not an expert by a long shot, but I've been playing with blueprints a little recently.
You can only register a blueprint on your flask app if the blueprint code has been imported into the current Python instance, for example:
from my_blueprint import blueprint_object
app.register_blueprint(blueprint_object, url_prefix='/my_blueprint')
meaning that all of the memory required for blueprint_object has been allocated, the __init__.py
file associated with my_blueprint
has been evaluated and everything is ready to go.
I experimented briefly with trying to load a blueprint in the app.before_first_request
method, but flask doesn't allow this, blueprints all need to be loaded before anything makes a request (and before_first_request
effectively runs just after that, but before any other code gets to play).
Blueprints are designed to provide extensible functionality to flask web-apps. I'm not sure why loading them in would be a waste of resources, unless you're only ever going to use a particular piece of functionality once, in which case, you might want to re-factor your application into a number of different apps that you can spin up as required.
Upvotes: 3