114 lines
4.0 KiB
Python
114 lines
4.0 KiB
Python
|
|
"""
|
|
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
|
|
from app.api.knowledge_base import knowledge_base_bp
|
|
from app.api.integration import integration_bp
|
|
from app.api.schedule_admin import schedule_admin_bp
|
|
from app.api.workspace_schedule import workspace_schedule_bp
|
|
from app.api.internal_jobs import internal_jobs_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')
|
|
# 知识库/数据清洗模块接口
|
|
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
|
# 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件)
|
|
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
|
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
|
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
|
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
|
|
|
# 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)
|
|
from app.services.schedule.scheduler_service import start_scheduler
|
|
start_scheduler(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 '<h1><p>Internal Server Error</p></h1>', 500
|
|
message = str(exc).strip() or 'Internal server error'
|
|
return jsonify({'error': message}), 500
|
|
|
|
return app
|