refactor(backend): 后端重构初步设想

This commit is contained in:
sophie committed 2026-06-17 11:24:54 +08:00
1 parent b69d549b2c
commit 21b8c24815
96 files changed
+1592

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/__init__.py
用途:横切能力包入口(errors、response、auth、config、db)。
逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/auth/__init__.py
用途:认证与当前用户解析包入口。
逻辑:api 层通过 get_current_user 获取 User;Wave 1 自 auth_jwt.py 迁入 jwt.py。
"""
+39
View File
@@ -0,0 +1,39 @@
"""
backend/app/core/auth/context.py
用途:从 Flask g/request 解析请求上下文(request_id、user),供 api 层薄封装。
逻辑:Wave 3 拆分 user/chat 路由时,将重复 auth 逻辑收敛到本模块。
"""
from __future__ import annotations
from typing import Any
def get_request_id() -> str | None:
"""
读取当前请求的 X-Request-Id 或 g.request_id。
核心逻辑:延迟 import flask.g,避免 services 层依赖。
Returns:
request_id 字符串,无上下文时返回 None。
"""
try:
from flask import g
return getattr(g, 'request_id', None)
except RuntimeError:
return None
def get_optional_config(key: str, default: Any = None) -> Any:
"""
读取 Flask app.config 项(仅 api / jobs context 使用)。
Args:
key: config 键名。
default: 无 app context 时的默认值。
"""
try:
from flask import current_app
return current_app.config.get(key, default)
except RuntimeError:
return default
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/auth/jwt.py
用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。
逻辑:api 路由与 decorators 调用 get_current_user()。
"""
from app.auth_jwt import get_current_user # noqa: F401
__all__ = ['get_current_user']
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/config/__init__.py
用途:应用配置包入口(settings、env_persistence)。
逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。
"""
@@ -0,0 +1,9 @@
"""
backend/app/core/config/env_persistence.py
用途:DB 持久化运行时配置(Wave 1 自 app/env_persistence.py 迁入)。
逻辑:before_request 调用 apply_env_settings 刷新 app.config。
"""
from app.env_persistence import apply_env_settings # noqa: F401
__all__ = ['apply_env_settings']
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/config/settings.py
用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。
逻辑:create_app(config_name) 通过 config[config_name] 加载。
"""
from app.config import ACTIVE_ENV_NAME, config # noqa: F401
__all__ = ['config', 'ACTIVE_ENV_NAME']
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/db/__init__.py
用途:数据库会话工具包入口。
逻辑:Wave 1 提供 run_with_retry;sequence 工具供迁移/运维脚本使用。
"""
+7
View File
@@ -0,0 +1,7 @@
"""
backend/app/core/db/sequence.py
用途:PostgreSQL 序列修复工具(Wave 1 自 services/db_sequence.py 迁入)。
逻辑:迁移脚本与 check_schema_drift 调用。
"""
from app.services.db_sequence import * # noqa: F403
+28
View File
@@ -0,0 +1,28 @@
"""
backend/app/core/db/session.py
用途:数据库会话辅助(重试、只读查询封装)。
逻辑:Wave 1 从 api/user.py、knowledge_base.py 等抽取 _run_db_with_retry 模式。
"""
from __future__ import annotations
from collections.abc import Callable
from typing import TypeVar
T = TypeVar('T')
def run_with_retry(fn: Callable[[], T], *, max_attempts: int = 3) -> T:
"""
在数据库短暂失败时重试可调用对象。
核心逻辑:捕获 OperationalError/DisconnectionError 后 rollback 并重试。
Args:
fn: 无参 callable,内部使用 db.session。
max_attempts: 最大尝试次数。
Returns:
fn 的返回值。
Raises:
最后一次失败的异常。
"""
# [STEP 1] Wave 0 占位:Wave 1 从 user.py / knowledge_base.py 抽取实现
return fn()
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/decorators.py
用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。
逻辑:api 层路由使用 @require_admin、@require_agent_permission。
"""
from app.decorators import require_admin, require_agent_permission # noqa: F401
__all__ = ['require_admin', 'require_agent_permission']
+26
View File
@@ -0,0 +1,26 @@
"""
backend/app/core/errors.py
用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。
依赖:无 Flask 依赖。
逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。
"""
from app.errors import ( # noqa: F401 — Wave 1: 实现迁入本文件后删除 app/errors.py shim
AppError,
ConflictError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
)
__all__ = [
'AppError',
'ValidationError',
'UnauthorizedError',
'ForbiddenError',
'NotFoundError',
'ConflictError',
'ServiceUnavailableError',
]
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/response.py
用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。
逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。
"""
from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401
__all__ = ['error_payload', 'ok', 'utc_iso_now']