This tutorial aims to help you build modular Flask application. The main goal of building a project in this manner is to factor this one in multiple subapplications. What can help you work on one without breaking all in case of a problem. The only prerequisite for understanding it is a working Flask application.
For those who don't know what Flask is, it's a lightweight web framework written in Python. You can read a good introduction to it there: Flask - An introduction to Python's lightweight web framework
Flask provides multiple ways to deal with many applications in only one project. For instance, imagine you have to build a blog engine, it can have a frontend which lists the blog posts, and a backend which allows you to manage your posts (publish, remove or modify). Which means you need two applications.
One of the solutions offered by Flask is Blueprints. This system allows you to link a subapplication to a route. Keeping the example of the blog engine, you can have the frontend application linked to
'/' route and the backend, to the
Let's code it
In pratice, it's really simple to set the blueprints up.
First, you have to create folders for each subapplication, their name matching the subapp's name, for a better comprehension. Add a
__init__.py file to each folder to help Python recognize them as modules. This file's content it's practically the same for the two apps.
from flask import Blueprint frontend_blueprint = Blueprint('frontend',__name__,template_folder='templates')
from flask import Blueprint backend_blueprint = blueprint('frontend',__name__,template_folder='templates')
As you see, only the first argument given to
The given arguments are, in the order: the name of the blueprint, the logical Python module corresponding to the Blueprint(in this example, it will be the frontend/backend module), the name of the folder which will contain the templates.
At this point, the blueprints are created but the Flask application doesn't know them yet. So, the last step is to register them. To do so, edit your application's
- Register the frontend subapplication
from frontend import frontend_blueprint app.register_blueprint(frontend, url_prefix='')
- Register the backend subapplication
from backendend import backend_blueprint app.register_blueprint(backend, url_prefix='/administration')
After this is done, in function of what the user types as url in his browser, the application will delegate the views to the matching blueprint. In our case, if the typed url is
frontend blueprint will be called. But if it is
http://myawesomewebsi.te/administration/hello, it's the
backend blueprint which will manage the view. Finally, you have to know that Blueprints acts like application. So, if the
backend/views file, you can use the
@backend.route('your route') to define routes, by example.