How to split a Flask application into parts
How to split a Flask application into parts
Introduction
An application is split into parts with blueprints.
You can read about them in more detail
here
.
This article is a step-by-step guide
Prerequisites
You have the main file __init__.py or app.py in which you have already created the Flask application
The urls are served with @app.route
Suppose you have a group of urls like
@app.route('/first/1', methods = ['GET'])
…
@app.route('/first/2', methods = ['GET'])
…
@app.route('/first/3', methods = ['GET'])
…
and a group of urls like
@app.route('/second/1', methods = ['GET'])
…
@app.route('/second/2', methods = ['GET'])
…
@app.route('/second/3', methods = ['GET'])
…
The urls that start with second you want to move into a separate sub-application, or you simply want to split the main file into parts so that the code is easier to find.
You have to do several things, the first of which is to create a new .py file
A new file
Next to the main file create a new file second.py
Import there everything you needed for it to work + functools
From flask be sure to import Blueprint
it is the key module for this operation.
import functools
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash
After the import add the line
bp = Blueprint('api', __name__, url_prefix='/second')
url_prefix='/second' means that all urls in this sub-application start with second
Add your urls, but replace @app. with @bp. and there is no need to write second/ any more
@bp.route('/1', methods = ['GET'])
…
@bp.route('/2', methods = ['GET'])
…
@bp.route('/3', methods = ['GET'])
…
The file second.py is ready
Registering a new blueprint
Now in the main file, which is most likely called __init__.py, delete the moved urls
And register the new sub-application by declaring its blueprint
from . import second
app.register_blueprint(second.bp)
url_for
You have most likely used url_for, and in the original file it looked something like this:
{{ url_for('second/1') }}
But now / has to be replaced with .
{{ url_for('second.1') }}
For the sake of order it also makes sense to move the templates into a separate folder templates/
open_resource
If you used to write with app.open_resource, now you have to write with bp.open_resource
For example:
def load_db():
with bp.open_resource('file.json') as f:
return json.load(f)
| Python | |
| Flask | |
| Running Flask on hosting | |
| Running Flask on a Linux server | |
| The first Flask project | |
| Jinja templates | |
| Flask FAQ | |
| Web Forms | |
| Errors |
Article author: Andrei Olegovich