Files
syops/backend/app/__init__.py
T
2026-04-20 09:08:58 +08:00

73 lines
2.1 KiB
Python

"""
backend/app/__init__.py
应用工厂
"""
import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from app.config import config
db = SQLAlchemy()
migrate = Migrate()
logger = logging.getLogger(__name__)
def _apply_persisted_settings(app: Flask) -> None:
"""Pull the latest runtime-editable settings into ``app.config``.
Reads from the database first, then ``backend/.env``. Tolerates the
common case where the table does not yet exist (fresh deploy before
``flask db upgrade`` runs).
"""
from app.env_persistence import apply_env_settings
try:
applied = apply_env_settings()
except Exception as exc: # pragma: no cover - defensive
logger.warning('Failed to refresh persisted settings: %s', exc)
return
for key, value in applied.items():
app.config[key] = value
def create_app(config_name='default'):
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
migrate.init_app(app, db)
CORS(app) # 允许跨域
# 注册 Blueprints
from app.api.chat import chat_bp
from app.api.admin import admin_bp
from app.api.agents import agents_bp
from app.api.user import user_bp
# 聊天相关接口
app.register_blueprint(chat_bp, url_prefix='/api/chat')
# 管理员相关接口
app.register_blueprint(admin_bp, url_prefix='/api/admin')
# 普通用户可见的 Agent 列表接口
app.register_blueprint(agents_bp, url_prefix='/api/agents')
# 当前用户相关接口(首页、常用问题等)
app.register_blueprint(user_bp, url_prefix='/api/user')
# Eagerly load persisted runtime settings so the very first request after
# a worker boot already sees the admin-saved configuration (otherwise the
# window between worker boot and the first ``before_request`` would still
# serve the defaults baked into config.py / the image).
with app.app_context():
_apply_persisted_settings(app)
@app.before_request
def _sync_persisted_settings():
_apply_persisted_settings(app)
return app