228 lines
8.3 KiB
Python
228 lines
8.3 KiB
Python
"""
|
|
backend/app/__init__.py
|
|
应用工厂:创建 Flask 应用、注册蓝图并挂载全局异常与响应处理。
|
|
"""
|
|
import logging
|
|
import uuid
|
|
|
|
from flask import Flask, jsonify, request, g
|
|
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
|
|
from app.errors import AppError
|
|
from app.response_utils import error_payload, utc_iso_now
|
|
|
|
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.workspace_shipping_notice import workspace_shipping_notice_bp
|
|
from app.api.workspace_file_check import workspace_file_check_bp
|
|
from app.api.internal_jobs import internal_jobs_bp
|
|
from app.api.shipping_notice_tools import shipping_notice_bp
|
|
from app.api.file_check_tools import file_check_bp
|
|
from app.api.speech import speech_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(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
|
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
|
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
|
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
|
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
|
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
|
|
|
# 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)
|
|
from app.cli.faq_commands import init_app as init_faq_cli
|
|
init_faq_cli(app)
|
|
|
|
@app.before_request
|
|
def _sync_persisted_settings():
|
|
_apply_persisted_settings(app)
|
|
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
|
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
|
|
|
@app.after_request
|
|
def _wrap_success_response(resp):
|
|
if not bool(app.config.get('ENABLE_API_ENVELOPE', False)):
|
|
return resp
|
|
if not request.path.startswith('/api/'):
|
|
return resp
|
|
if resp.is_streamed:
|
|
return resp
|
|
if resp.status_code < 200 or resp.status_code >= 300:
|
|
return resp
|
|
if not (resp.mimetype or '').startswith('application/json'):
|
|
return resp
|
|
try:
|
|
payload = resp.get_json(silent=True)
|
|
except Exception:
|
|
payload = None
|
|
if isinstance(payload, dict) and 'success' in payload:
|
|
return resp
|
|
wrapped = {
|
|
'success': True,
|
|
'data': payload,
|
|
'request_id': getattr(g, 'request_id', None),
|
|
'timestamp': utc_iso_now(),
|
|
}
|
|
wrapped_resp = jsonify(wrapped)
|
|
wrapped_resp.status_code = resp.status_code
|
|
for key, value in resp.headers.items():
|
|
lower = key.lower()
|
|
if lower in ('content-length', 'content-type'):
|
|
continue
|
|
wrapped_resp.headers[key] = value
|
|
return wrapped_resp
|
|
|
|
def _should_return_json_error() -> bool:
|
|
if request.path.startswith('/api/'):
|
|
return True
|
|
accepted = request.headers.get('Accept', '')
|
|
return 'application/json' in accepted.lower()
|
|
|
|
def _log_api_error(
|
|
*,
|
|
code: str,
|
|
message: str,
|
|
status: int,
|
|
details: dict | None = None,
|
|
exc: Exception | None = None,
|
|
) -> None:
|
|
request_id = getattr(g, 'request_id', None)
|
|
log_kwargs = {
|
|
'method': request.method,
|
|
'path': request.path,
|
|
'status': status,
|
|
'code': code,
|
|
'message': message,
|
|
'request_id': request_id,
|
|
'details': details or {},
|
|
}
|
|
log_text = (
|
|
'API error %(method)s %(path)s status=%(status)s code=%(code)s '
|
|
'message=%(message)s request_id=%(request_id)s details=%(details)s'
|
|
)
|
|
if status >= 500:
|
|
app.logger.error(log_text, log_kwargs, exc_info=exc)
|
|
else:
|
|
app.logger.warning(log_text, log_kwargs)
|
|
|
|
@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'
|
|
code_num = int(exc.code or 500)
|
|
code_map = {
|
|
400: 'VALIDATION.INVALID_PARAM',
|
|
401: 'AUTH.UNAUTHORIZED',
|
|
403: 'AUTH.FORBIDDEN',
|
|
404: 'RESOURCE.NOT_FOUND',
|
|
409: 'RESOURCE.CONFLICT',
|
|
429: 'SYSTEM.RATE_LIMITED',
|
|
}
|
|
code = code_map.get(code_num, 'SYSTEM.HTTP_ERROR')
|
|
_log_api_error(code=code, message=str(message), status=code_num, exc=exc)
|
|
payload = error_payload(
|
|
code=code,
|
|
message=str(message),
|
|
request_id=getattr(g, 'request_id', None),
|
|
)
|
|
return jsonify(payload), code_num
|
|
|
|
@app.errorhandler(AppError)
|
|
def _handle_app_error(exc: AppError):
|
|
_log_api_error(
|
|
code=exc.code,
|
|
message=exc.message,
|
|
status=exc.http_status,
|
|
details=exc.details,
|
|
exc=exc,
|
|
)
|
|
payload = error_payload(
|
|
code=exc.code,
|
|
message=exc.message,
|
|
request_id=getattr(g, 'request_id', None),
|
|
details=exc.details,
|
|
retryable=exc.retryable,
|
|
)
|
|
return jsonify(payload), exc.http_status
|
|
|
|
@app.errorhandler(Exception)
|
|
def _handle_unexpected_exception(exc: Exception):
|
|
_log_api_error(
|
|
code='SYSTEM.INTERNAL_ERROR',
|
|
message='Internal server error',
|
|
status=500,
|
|
exc=exc,
|
|
)
|
|
if not _should_return_json_error():
|
|
return '<h1><p>Internal Server Error</p></h1>', 500
|
|
payload = error_payload(
|
|
code='SYSTEM.INTERNAL_ERROR',
|
|
message='Internal server error',
|
|
request_id=getattr(g, 'request_id', None),
|
|
)
|
|
return jsonify(payload), 500
|
|
|
|
return app
|