Lately I came to find Django a bit top heavy for one of my projects, so I chose Flask as a lighter and smaller alternative.
After fiddling with the tutorials for a bit I wanted to have a setup with several modules. Suprisingly that wasn’t as easy to do as the snippets and examples showed several options and configurations and… So, this is what worked for me. May not be the true gospel but I wanted modules to be set to certain urls like mounted apps in padrino.
This is what I came up with:
+ Project -- start.py + module1 -- __init__.py -- app.py + module2 -- __init__.py -- app.py
So module1 and 2 are two functional units which should answer to specific prefixes (localhost:5000/module1 and localhost:5000/module2) and start.py is the file to run the whole show.
I used flask-blueprint to get it all under the roof.
First let’s get the modules to behave like modules. In module1/app.py I added:
from flask import Blueprint app1 = Blueprint('app1', __name__) ... @app1.route ...
For module2 app.py looks similar except that app1 is changed to app2.
So, now we have the blueprints, of which the project does not know yet. In fact we don’t have any app so far. All the nutrs and bolts go into start.py:
from flask import Flask from module1.app import app1 from module2.app import app2 project = Flask(__name__) project.register_blueprint(app1, url_prefix='/path1') project.register_blueprint(app2. url_prefix='/path2') if __name__ == '__main__': project.run()
This is the beauty of blueprint (imho). Import the blueprint, register it and pu t it on a dedicated path.
Done. To modules in a flask-application.