Why Are Flask Blueprints Needed?¶
When developing a simple Flask application, we might write all the code in a single file, for example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello World"
@app.route('/user')
def user_profile():
return "User Profile"
@app.route('/order')
def order_list():
return "Order List"
if __name__ == '__main__':
app.run(debug=True)
However, as the application becomes more complex (e.g., with dozens or even hundreds of routes), the code can become a tangled mess, making it difficult to maintain and extend. At this point, modularizing the code becomes crucial.
Flask Blueprints are tools designed to solve this problem. They allow us to split the application into multiple independent modules based on functionality (such as user modules, order modules, blog modules, etc.), resulting in a clearer and more maintainable code structure.
What Are Flask Blueprints?¶
A blueprint is essentially a “collection of operations”. It can contain routes, templates, static files, etc., but it cannot run directly. It needs to be registered with the main application to take effect. In simple terms, a blueprint “packages” routes and view functions that were originally scattered in the main application into smaller modules, enabling independent development, testing, and maintenance of each module.
How to Use Flask Blueprints?¶
1. Create Blueprint Instances¶
First, we need to create a blueprint object. The syntax is as follows:
from flask import Blueprint
# Create blueprint instances
user_bp = Blueprint('user', __name__, url_prefix='/user')
order_bp = Blueprint('order', __name__, url_prefix='/order')
- First parameter: The unique identifier of the blueprint (a string, e.g.,
'user'), used to distinguish different blueprints. - Second parameter: Typically uses
__name__, representing the name or path of the current module. Flask will use this parameter to locate the blueprint’s templates and static files. - url_prefix (optional): Adds a unified URL prefix (e.g.,
/user) to all routes under the blueprint, avoiding route conflicts between different modules.
2. Define Routes in the Blueprint¶
Defining routes in a blueprint is similar to regular routes, but we prefix the route decorator with the blueprint object:
# user_bp.py (routes for the user module)
@user_bp.route('/profile')
def user_profile():
return "User Profile Page"
@user_bp.route('/login')
def user_login():
return "User Login Page"
# order_bp.py (routes for the order module)
@order_bp.route('/list')
def order_list():
return "Order List Page"
@order_bp.route('/detail/<int:order_id>')
def order_detail(order_id):
return f"Order Details: {order_id}"
3. Register the Blueprint with the Main Application¶
Finally, register the blueprint with the main Flask application:
from flask import Flask
from user_bp import user_bp # Import the user module blueprint
from order_bp import order_bp # Import the order module blueprint
app = Flask(__name__)
# Register blueprints with the main application
app.register_blueprint(user_bp)
app.register_blueprint(order_bp)
if __name__ == '__main__':
app.run(debug=True)
4. Blueprint Templates and Static Files¶
If a blueprint needs to use its own templates or static files, specify the template_folder and static_folder parameters when creating the blueprint:
# Create a blueprint with specified template and static folders
user_bp = Blueprint('user', __name__,
url_prefix='/user',
template_folder='templates', # Blueprint's template folder
static_folder='static') # Blueprint's static folder
- Template Path: If the blueprint’s template folder is named
templates, Flask will prioritize looking for templates in the blueprint’s folder (e.g.,user/templates/login.html) when rendering templates in view functions, and then check the main application’s template folder if not found. - Static File Path: To reference a blueprint’s static file in a template, use
url_for('blueprint_name.static', filename='path'), for example:
<link rel="stylesheet" href="{{ url_for('user.static', filename='css/style.css') }}">
Advantages of Blueprints¶
1. Modular Code Splitting¶
Routes and view functions that were once concentrated in a single file are split into independent modules, each responsible for specific functionality, avoiding code chaos.
2. Facilitate Team Collaboration¶
Different developers can work on different modules (e.g., user module, order module) in parallel without interfering with each other, reducing collaboration costs.
3. Simplify Testing and Maintenance¶
Each module can be tested independently, making problem localization simpler, and code updates have a smaller impact range.
4. Unified Route Prefix Management¶
Using the url_prefix parameter automatically adds a unified prefix (e.g., /user) to all routes, avoiding route conflicts between different modules.
Summary¶
Flask Blueprints are a core tool for modular development. They allow splitting complex Flask applications into multiple independent functional modules. This article covers the basic usage of blueprints: creating instances, defining routes, registering with the application, and handling templates and static files. Mastering blueprints enables you to organize project structures more efficiently and lay a solid foundation for large-scale application development.
For beginners, it is recommended to start with simple module splitting and gradually apply blueprint concepts in actual projects to develop the habit of modular development.