""" backend/app/__init__.py 应用工厂 """ import logging from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_cors import CORS from werkzeug.exceptions import HTTPException 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) def _should_return_json_error() -> bool: if request.path.startswith('/api/'): return True accepted = request.headers.get('Accept', '') return 'application/json' in accepted.lower() @app.errorhandler(HTTPException) def _handle_http_exception(exc: HTTPException): if not _should_return_json_error(): return exc message = exc.description or exc.name or 'HTTP error' return jsonify({'error': str(message)}), int(exc.code or 500) @app.errorhandler(Exception) def _handle_unexpected_exception(exc: Exception): app.logger.exception( 'Unhandled exception on %s %s', request.method, request.path, exc_info=exc, ) if not _should_return_json_error(): return '
Internal Server Error
', 500 message = str(exc).strip() or 'Internal server error' return jsonify({'error': message}), 500 return app