Files
2026-09-23 13:56:49 +08:00

35 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
应用工厂模块(Application Factory Pattern)
- 延迟创建 Flask 实例,支持测试时传入不同配置
- 扩展对象在模块顶层创建但不绑定 app,通过 init_app() 延迟绑定
- 这种模式是 Flask 官方推荐的最佳实践,避免循环导入
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from app.config import Config
# ✅ 扩展实例在工厂外部创建,不与任何 app 绑定
# 这样可以在测试中创建多个 app 实例共享同一套扩展
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_class=Config):
"""
应用工厂函数
:param config_class: 配置类,默认使用 Config,测试时可替换为 TestingConfig
:return: 配置完成的 Flask 应用实例
"""
app = Flask(__name__)
app.config.from_object(config_class)
# 将扩展绑定到当前 app 实例
db.init_app(app)
migrate.init_app(app, db)
# 注册蓝图(放在这里避免循环导入:蓝图引用 db → db 在工厂中初始化)
from app.routes.user import user_bp
app.register_blueprint(user_bp, url_prefix='/api/users')
return app