Using Flask blueprints, you can break up your application in multiple files which can be put back together into a larger application.
Below is a sample application broken into 3 files that demonstrates just that:
- file1 : define a /hello route
- file2 : define a /world route
- file3 : main app, acts as a glue by using register_blueprint function to integrate the apps in file1 and file2
file1: defines app_file1 with route /hello
from flask import Blueprint, render_template, session,abort
app_file1 = Blueprint('app_file1',__name__)
@app_file1.route("/hello")
def hello():
return "Hello World from app 1!"
file2: defines app_file2 with route /world
from flask import Blueprint, render_template, session,abort
app_file2 = Blueprint('app_file2',__name__)
@app_file2.route("/world")
def world():
return "Hello World from app 2!"
file3: main app
from flask import Flask
from file1 import app_file1
from file2 import app_file2
main_app = Flask(__name__)
main_app.register_blueprint(app_file1)
main_app.register_blueprint(app_file2)
Note: To simplify things, for this example are kept in a single directory. In a larger application, you would want to further break things into directories/modules. Using modules is extra step allows to only expose the functionality you want public, do extra initialization and avoid circular dependencies.
It is also good practice to have additional folders for things like data access like sqlalchemy models. It's always good to encapsulate files that have common functionality like a payment processing into a module for potential reuse, code clarity and maintenance
If your application has a large amount of views, you may want to have additional subfolders as well