Flask蓝图与模块化 #

一、蓝图概述 #

1.1 什么是蓝图 #

蓝图是Flask中组织应用的一种方式,它允许你将相关的视图、模板和静态文件组织在一起,形成独立的功能模块。

text
Flask应用
├── 主蓝图(main)
├── 认证蓝图(auth)
├── API蓝图(api)
└── 管理蓝图(admin)

1.2 蓝图的作用 #

作用 说明
模块化 将应用拆分为独立模块
代码组织 按功能组织代码
复用性 蓝图可在多个应用中复用
维护性 便于维护和扩展
团队协作 不同团队负责不同蓝图

1.3 蓝图与应用的区别 #

特性 应用 蓝图
配置 有独立配置 共享应用配置
路由 直接注册 需要注册到应用
模板 全局模板 可有独立模板
静态文件 全局静态文件 可有独立静态文件
生命周期 应用启动时创建 可延迟注册

二、创建蓝图 #

2.1 基本创建 #

python
from flask import Blueprint

# 创建蓝图
# 参数:蓝图名称、模块名
auth = Blueprint('auth', __name__)

# 定义路由
@auth.route('/login')
def login():
    return '登录页面'

@auth.route('/register')
def register():
    return '注册页面'

2.2 蓝图参数 #

python
auth = Blueprint(
    'auth',                    # 蓝图名称
    __name__,                  # 模块名
    url_prefix='/auth',        # URL前缀
    subdomain='auth',          # 子域名
    url_defaults={'page': 1},  # URL默认值
    static_folder='static',    # 静态文件目录
    template_folder='templates', # 模板目录
    root_path=None             # 根路径
)

2.3 完整蓝图模块 #

text
app/
├── auth/
│   ├── __init__.py      # 创建蓝图
│   ├── routes.py        # 路由定义
│   ├── forms.py         # 表单类
│   ├── models.py        # 数据模型
│   ├── templates/       # 蓝图模板
│   │   └── auth/
│   │       ├── login.html
│   │       └── register.html
│   └── static/          # 蓝图静态文件
│       └── auth/
│           └── css/
│               └── login.css
└── __init__.py

auth/init.py:

python
from flask import Blueprint

auth = Blueprint('auth', __name__, url_prefix='/auth')

from . import routes

auth/routes.py:

python
from flask import render_template, redirect, url_for
from . import auth

@auth.route('/login')
def login():
    return render_template('auth/login.html')

@auth.route('/register')
def register():
    return render_template('auth/register.html')

三、注册蓝图 #

3.1 基本注册 #

python
from flask import Flask
from auth import auth

app = Flask(__name__)

# 注册蓝图
app.register_blueprint(auth)

# 访问 /auth/login
# 访问 /auth/register

3.2 注册时指定前缀 #

python
# 创建时不指定前缀
auth = Blueprint('auth', __name__)

# 注册时指定前缀
app.register_blueprint(auth, url_prefix='/user')

# 访问 /user/login

3.3 注册选项 #

python
app.register_blueprint(
    auth,
    url_prefix='/auth',           # URL前缀
    subdomain='api',              # 子域名
    url_defaults={'v': 1},        # 默认值
    host='api.example.com'        # 主机名
)

3.4 多个蓝图注册 #

python
from auth import auth
from api import api
from admin import admin

app.register_blueprint(auth, url_prefix='/auth')
app.register_blueprint(api, url_prefix='/api')
app.register_blueprint(admin, url_prefix='/admin')

四、蓝图路由 #

4.1 路由定义 #

python
from flask import Blueprint

auth = Blueprint('auth', __name__)

@auth.route('/login')
def login():
    return '登录'

@auth.route('/register')
def register():
    return '注册'

@auth.route('/logout')
def logout():
    return '登出'

4.2 动态路由 #

python
@auth.route('/user/<username>')
def profile(username):
    return f'用户: {username}'

@auth.route('/post/<int:post_id>')
def post(post_id):
    return f'文章: {post_id}'

4.3 HTTP方法 #

python
@auth.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return '处理登录'
    return '显示登录表单'

4.4 URL构建 #

python
from flask import url_for

# 蓝图中的端点格式: 蓝图名.视图函数名
url_for('auth.login')      # /auth/login
url_for('auth.register')   # /auth/register
url_for('auth.profile', username='zhangsan')  # /auth/user/zhangsan

五、蓝图模板 #

5.1 模板目录结构 #

text
app/
├── templates/              # 全局模板
│   └── base.html
└── auth/
    └── templates/          # 蓝图模板
        └── auth/
            ├── login.html
            └── register.html

5.2 使用蓝图模板 #

python
# auth/routes.py
@auth.route('/login')
def login():
    return render_template('auth/login.html')

5.3 模板继承 #

templates/base.html:

html
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <nav>
        <a href="{{ url_for('main.index') }}">首页</a>
        <a href="{{ url_for('auth.login') }}">登录</a>
    </nav>
    {% block content %}{% endblock %}
</body>
</html>

auth/templates/auth/login.html:

html
{% extends "base.html" %}

{% block title %}登录{% endblock %}

{% block content %}
<h1>登录</h1>
<form method="POST">
    <input type="text" name="username" placeholder="用户名">
    <input type="password" name="password" placeholder="密码">
    <button type="submit">登录</button>
</form>
{% endblock %}

5.4 模板上下文 #

python
@auth.context_processor
def inject_auth_vars():
    return {
        'auth_var': 'value'
    }

六、蓝图静态文件 #

6.1 静态文件目录 #

text
app/
├── static/                 # 全局静态文件
│   ├── css/
│   └── js/
└── auth/
    └── static/             # 蓝图静态文件
        └── auth/
            └── css/
                └── login.css

6.2 配置蓝图静态文件 #

python
auth = Blueprint(
    'auth',
    __name__,
    static_folder='static',
    static_url_path='/auth/static'
)

6.3 引用蓝图静态文件 #

html
<!-- 在模板中 -->
<link rel="stylesheet" href="{{ url_for('auth.static', filename='auth/css/login.css') }}">

七、蓝图高级用法 #

7.1 蓝图中间件 #

python
@auth.before_request
def before_request():
    # 在每个请求前执行
    pass

@auth.after_request
def after_request(response):
    # 在每个请求后执行
    return response

@auth.teardown_request
def teardown_request(exception):
    # 请求结束后执行
    pass

7.2 蓝图错误处理 #

python
@auth.errorhandler(404)
def page_not_found(e):
    return '认证页面不存在', 404

@auth.errorhandler(500)
def internal_error(e):
    return '认证内部错误', 500

7.3 蓝图URL默认值 #

python
api = Blueprint('api', __name__, url_defaults={'version': 'v1'})

@api.route('/users')
def users(version):
    return f'API {version} 用户列表'

# 访问 /users → API v1 用户列表

7.4 嵌套蓝图 #

python
from flask import Blueprint

# 父蓝图
api = Blueprint('api', __name__, url_prefix='/api')

# 子蓝图
v1 = Blueprint('v1', __name__, url_prefix='/v1')
v2 = Blueprint('v2', __name__, url_prefix='/v2')

# 注册子蓝图到父蓝图
api.register_blueprint(v1)
api.register_blueprint(v2)

# 注册父蓝图到应用
app.register_blueprint(api)

# 访问 /api/v1/...
# 访问 /api/v2/...

八、完整蓝图示例 #

8.1 项目结构 #

text
myapp/
├── app/
│   ├── __init__.py
│   ├── models.py
│   ├── main/
│   │   ├── __init__.py
│   │   ├── routes.py
│   │   ├── forms.py
│   │   └── templates/
│   │       └── main/
│   │           ├── index.html
│   │           └── about.html
│   ├── auth/
│   │   ├── __init__.py
│   │   ├── routes.py
│   │   ├── forms.py
│   │   └── templates/
│   │       └── auth/
│   │           ├── login.html
│   │           └── register.html
│   ├── api/
│   │   ├── __init__.py
│   │   ├── users.py
│   │   └── posts.py
│   └── templates/
│       └── base.html
├── config.py
├── run.py
└── requirements.txt

8.2 应用工厂 #

app/init.py:

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app(config_name='default'):
    app = Flask(__name__)
    
    # 加载配置
    from config import config
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    
    # 注册蓝图
    from app.main import main
    from app.auth import auth
    from app.api import api
    
    app.register_blueprint(main)
    app.register_blueprint(auth, url_prefix='/auth')
    app.register_blueprint(api, url_prefix='/api')
    
    return app

8.3 主蓝图 #

app/main/init.py:

python
from flask import Blueprint

main = Blueprint('main', __name__)

from . import routes

app/main/routes.py:

python
from flask import render_template
from . import main

@main.route('/')
def index():
    return render_template('main/index.html')

@main.route('/about')
def about():
    return render_template('main/about.html')

8.4 认证蓝图 #

app/auth/init.py:

python
from flask import Blueprint

auth = Blueprint('auth', __name__)

from . import routes

app/auth/routes.py:

python
from flask import render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user
from . import auth
from .forms import LoginForm, RegisterForm

@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # 登录逻辑
        flash('登录成功')
        return redirect(url_for('main.index'))
    return render_template('auth/login.html', form=form)

@auth.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        # 注册逻辑
        flash('注册成功')
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)

@auth.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('main.index'))

8.5 API蓝图 #

app/api/init.py:

python
from flask import Blueprint

api = Blueprint('api', __name__)

from . import users, posts

app/api/users.py:

python
from flask import jsonify, request
from . import api

@api.route('/users', methods=['GET'])
def get_users():
    users = [
        {'id': 1, 'name': '张三'},
        {'id': 2, 'name': '李四'},
    ]
    return jsonify(users)

@api.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = {'id': user_id, 'name': '张三'}
    return jsonify(user)

@api.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    return jsonify({'id': 3, 'name': data['name']}), 201

九、蓝图最佳实践 #

9.1 命名规范 #

python
# 蓝图名称使用简短的标识符
auth = Blueprint('auth', __name__)      # 认证
api = Blueprint('api', __name__)        # API
admin = Blueprint('admin', __name__)    # 管理
blog = Blueprint('blog', __name__)      # 博客

9.2 目录组织 #

text
# 每个蓝图一个目录
app/
├── auth/          # 认证蓝图
├── api/           # API蓝图
├── admin/         # 管理蓝图
└── main/          # 主蓝图

9.3 导入顺序 #

python
# auth/__init__.py
from flask import Blueprint

auth = Blueprint('auth', __name__)

# 在蓝图创建后导入路由,避免循环导入
from . import routes

9.4 配置分离 #

python
# 每个蓝图可以有独立配置
auth = Blueprint('auth', __name__)

@auth.record_once
def on_load(state):
    # 蓝图加载时执行
    state.app.config.setdefault('AUTH_SETTING', 'default')

十、总结 #

10.1 核心要点 #

要点 说明
创建蓝图 Blueprint(‘name’, name)
注册蓝图 app.register_blueprint(blueprint)
URL前缀 url_prefix参数
端点名称 蓝图名.视图函数名
模板组织 可有独立模板目录
静态文件 可有独立静态文件目录

10.2 下一步 #

现在你已经掌握了蓝图与模块化,接下来让我们学习 Jinja2基础,了解Flask的模板系统!

最后更新:2026-03-28