Blueprint(蓝图)是 Flask 中用于组织大型应用程序的模块化方式,它允许你将应用程序分解为可重用的组件。
一、Blueprint 是什么? #
Blueprint 是 Flask 提供的一种组织应用程序代码的方式,它:
- 不是 Flask 应用程序,而是构建或扩展应用程序的蓝图
- 可以包含路由、模板、静态文件等
- 可以延迟注册到应用程序上
二、为什么需要 Blueprint? #
- 模块化开发:将大型应用分解为多个蓝图模块
- 代码复用:可以在多个项目中复用蓝图
- 延迟绑定:蓝图可以在创建后稍后注册到应用
- URL 前缀:可以为整个蓝图设置统一的前缀
- 独立命名空间:模板和静态文件可以有独立目录
三、基本使用 #
1. 创建 Blueprint #
from flask import Blueprint
# 创建一个名为 'auth' 的蓝图
auth_bp = Blueprint(
'auth', # 蓝图名称
__name__, # 导入名称
url_prefix='/auth', # URL 前缀
template_folder='templates', # 蓝图专用模板目录
static_folder='static' # 蓝图专用静态文件目录
)2. 添加路由 #
@auth_bp.route('/login')
def login():
return 'Login Page'
@auth_bp.route('/logout')
def logout():
return 'Logout Page'3. 注册到应用 #
from flask import Flask
app = Flask(__name__)
app.register_blueprint(auth_bp)四、高级特性 #
1. URL 前缀 #
# 访问路径将是 /auth/login 和 /auth/logout
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')2. 静态文件和模板 #
auth_bp = Blueprint(
'auth',
__name__,
static_folder='static_auth', # 相对于蓝图模块的路径
template_folder='templates_auth'
)3. 请求钩子 #
@auth_bp.before_request
def before_auth_request():
print("This runs before each auth blueprint request")4. 错误处理器 #
@auth_bp.errorhandler(404)
def auth_not_found(error):
return "Auth-specific 404 page", 404五、实际项目结构示例 #
myapp/
├── app.py # 主应用
├── auth/ # 认证蓝图
│ ├── __init__.py # 创建蓝图
│ ├── routes.py # 路由
│ ├── templates/ # 蓝图专用模板
│ └── static/ # 蓝图专用静态文件
├── blog/ # 博客蓝图
│ ├── __init__.py
│ ├── routes.py
│ └── templates/
└── templates/ # 应用全局模板六、注册多个蓝图 #
from auth.routes import auth_bp
from blog.routes import blog_bp
app = Flask(__name__)
app.register_blueprint(auth_bp)
app.register_blueprint(blog_bp, url_prefix='/blog')七、蓝图资源组织 #
模板查找顺序:
- 先查找应用全局的
templates目录 - 然后查找蓝图的
template_folder指定目录
- 先查找应用全局的
静态文件:
- 蓝图静态文件可通过
blueprint_name.static访问 - 例如:
auth_bp.static对应auth/static/目录
- 蓝图静态文件可通过
八、最佳实践 #
- 每个功能模块使用一个独立的蓝图
- 为蓝图设置合理的 URL 前缀
- 大型项目可以将蓝图放在单独的 Python 包中
- 使用
url_for()时指定蓝图名称:url_for('auth.login') # 'auth' 是蓝图名称
Blueprint 是 Flask 中构建大型应用的推荐方式,它使你的代码更加模块化、可维护和可扩展。