Files
syops/backend/app/__init__.py
T
hugo 2d7bdecc43 feat(shipping-notice): 新增货代发货通知全流程业务功能
- 新增后端完整业务支持:数据库模型、API接口、核心服务与RPA对接逻辑
- 新增前端工作台页面、路由适配与多语言国际化
- 新增Dify自定义工具OpenAPI规范、Agent配置脚本与部署文档
- 新增发货Excel模板生成脚本与默认模板
- 修复测试配置文件中的环境变量命名错误
- 更新本地开发环境变量配置
2026-06-01 21:22:22 +08:00

118 lines
4.3 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.workspace_shipping_notice import workspace_shipping_notice_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.shipping_notice_tools import shipping_notice_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(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
# 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