I'm trying to create a simple, but not trivial application with Flask and I keep running into a situation which is not explained well in the docs.
I'd like my app to be split between different modules, but it looks like it's hard to access the main
app object (or
flask-sqlalchemy) from any other place than the main module. It looks like you have to really write your own way of treating it as a global that everything has access to, which requires some questionable code and a bit of time.
db are created at the level where the main application is instantiated and every example assumes they're available at the top level. But if I split different url handlers into different modules, I lose the ability to use
@app.route decorator. I can work around that with
app.add_url_rule('/...', some.module...), but then again, app is not passed to that function.
Same thing happens with the
db - I don't know if I should stick it into
g, or make it accessible via
app somehow. Doing that doesn't help me with moving the models into a separate module though - how am I supposed to access
db when importing them? All examples again assume it's just available as a local variable.
Am I missing something obvious, or am I trying to use flask for the wrong task here?
The answer to your question is blueprints. In fact, if you look at documentation, it is mentioned that blueprints are there to enable division of application in modules.
from flask import Blueprint mod = Blueprint(blueprint_name, __name__, template_folder="folder_name" static_folder="folder_name") @mod.route('/mymodule') def view(): # your code
from yourmodule import mod app.register_blueprint(mod)
This is the right way to divide app into modules. Check out blueprint docs for more details.
Moreover if you require to access app in any other module, you should use
current_app proxy of the app.
from flask import current_app
Check out this document which guides how to divide flask app into modules for large projects by the creator of flask.