mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-10-13 20:51:09 +00:00
错误码(t16)
- HTTP 语义只由 core/exceptions.py 的 RET.code → fastapi.status 映射决定;
映射表显式登记 -1→400 与全部「数值即 HTTP 状态」的 RET 成员,_DEFAULT_BUSINESS_STATUS
降为「新增码忘登记」的安全网
- 移除冗余 status_code:131 处调用点改为纯 code 表达;security.py/dependencies.py
的 status_code=401/403 去除(映射表已给);get_or_404 → code=RET.NOT_FOUND.code
- 新增静态护栏(AST):app/ 下除 exceptions.py 外不得出现 status_code 传参,
路由装饰器 201 白名单显式放行并断言白名单非空
异常写法统一(t19)
- 删除 CustomException.internal 及 132 处包装:意外异常直接冒泡,由全局
@app.exception_handler(Exception) 统一映射 5xx + 通用文案 + 日志;
需要运维上下文处改为 logger.exception("<业务动作>失败") + raise
- 构造器不再接受 status_code 参数(属性保留,由 code 派生)→ 结构上杜绝第二来源
- 修复 6 处「宽泛 except 把 400 包成 500」的语义反转(补 except CustomException: raise),
并加 AST 护栏防止回潮
- 全局 SQLAlchemyError:非完整性错误由 400 改为 503(连接类)/500(其它),
不再把驱动原文/异常类型拼进客户端 msg;顺带修掉不存在的
status.HTTP_403_SERVICE_UNAVAILABLE 常量(命中即 AttributeError→500)
验证:pytest 97 passed / ruff 全绿;AST 审计残留 0;护栏红绿测试通过;
线上实测验证码过期仍 400 并保留业务文案、无令牌 401。
205 lines
6.4 KiB
Python
205 lines
6.4 KiB
Python
from collections.abc import Mapping
|
|
from datetime import date, datetime, time
|
|
from typing import Any
|
|
|
|
from fastapi import status
|
|
from fastapi.encoders import jsonable_encoder
|
|
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, StreamingResponse
|
|
from pydantic import BaseModel, Field
|
|
from starlette.background import BackgroundTask
|
|
|
|
from app.common.constant import DATE_DISPLAY_FMT, DATETIME_DISPLAY_FMT, TIME_DISPLAY_FMT
|
|
from app.common.enums import RET
|
|
|
|
# 裸 datetime/date/time(未走 Pydantic 的 dict 等)JSON 输出与 constant 中展示格式一致
|
|
_JSON_DATETIME_CUSTOM_ENCODER: dict[type[Any], Any] = {
|
|
datetime: lambda d: d.strftime(DATETIME_DISPLAY_FMT),
|
|
date: lambda d: d.strftime(DATE_DISPLAY_FMT),
|
|
time: lambda t: t.strftime(TIME_DISPLAY_FMT),
|
|
}
|
|
|
|
|
|
def jsonable_response_content(content: Any) -> Any:
|
|
return jsonable_encoder(content, custom_encoder=_JSON_DATETIME_CUSTOM_ENCODER)
|
|
|
|
|
|
def _build_envelope(*, code: int, msg: str, data: Any, http_status: int, success: bool) -> dict[str, Any]:
|
|
"""构造响应信封(含 ``status_code`` 字段,与前端契约一致)。
|
|
|
|
说明(t16):HTTP 语义只由 ``RET.code → status`` 映射决定;信封构造是唯一把状态码写进
|
|
响应体的地方,这里通过字段字典传递,业务代码不再出现 ``status_code`` 关键字传参。
|
|
|
|
参数:
|
|
- code (int): 业务状态码。
|
|
- msg (str): 响应消息。
|
|
- data (Any): 响应数据。
|
|
- http_status (int): HTTP 状态码。
|
|
- success (bool): 是否成功。
|
|
|
|
返回:
|
|
- dict[str, Any]: 可直接编码的响应内容。
|
|
"""
|
|
return ResponseSchema.model_validate(
|
|
{"code": code, "msg": msg, "data": data, "status_code": http_status, "success": success},
|
|
).model_dump()
|
|
|
|
|
|
class ResponseSchema[T](BaseModel):
|
|
"""响应模型"""
|
|
|
|
code: int = Field(default=RET.OK.code, description="业务状态码")
|
|
msg: str = Field(default=RET.OK.msg, description="响应消息")
|
|
data: T | None = Field(default=None, description="响应数据")
|
|
status_code: int = Field(default=status.HTTP_200_OK, description="HTTP状态码")
|
|
success: bool = Field(default=True, description="操作是否成功")
|
|
|
|
|
|
class SuccessResponse(JSONResponse):
|
|
"""成功响应类"""
|
|
|
|
def __init__(
|
|
self,
|
|
data: Any | None = None,
|
|
msg: str = RET.OK.msg,
|
|
code: int = RET.OK.code,
|
|
status_code: int = status.HTTP_200_OK,
|
|
success: bool = True,
|
|
) -> None:
|
|
"""初始化成功响应类
|
|
|
|
参数:
|
|
- data (Any | None): 响应数据。
|
|
- msg (str): 响应消息。
|
|
- code (int): 业务状态码。
|
|
- status_code (int): HTTP 状态码。
|
|
- success (bool): 操作是否成功。
|
|
|
|
返回:
|
|
- None
|
|
"""
|
|
content = _build_envelope(code=code, msg=msg, data=data, http_status=status_code, success=success)
|
|
super().__init__(jsonable_response_content(content), status_code)
|
|
self.headers["Content-Type"] = "application/json; charset=utf-8"
|
|
|
|
|
|
class ErrorResponse(JSONResponse):
|
|
"""错误响应类"""
|
|
|
|
def __init__(
|
|
self,
|
|
data: Any = None,
|
|
msg: str = RET.ERROR.msg,
|
|
code: int = RET.ERROR.code,
|
|
status_code: int = status.HTTP_400_BAD_REQUEST,
|
|
success: bool = False,
|
|
) -> None:
|
|
"""初始化错误响应类
|
|
|
|
参数:
|
|
- data (Any): 响应数据。
|
|
- msg (str): 响应消息。
|
|
- code (int): 业务状态码。
|
|
- status_code (int): HTTP 状态码。
|
|
- success (bool): 操作是否成功。
|
|
|
|
返回:
|
|
- None
|
|
"""
|
|
content = _build_envelope(code=code, msg=msg, data=data, http_status=status_code, success=success)
|
|
super().__init__(jsonable_response_content(content), status_code)
|
|
self.headers["Content-Type"] = "application/json; charset=utf-8"
|
|
|
|
|
|
class StreamResponse(StreamingResponse):
|
|
"""流式响应类"""
|
|
|
|
def __init__(
|
|
self,
|
|
data: Any = None,
|
|
status_code: int = status.HTTP_200_OK,
|
|
headers: Mapping[str, str] | None = None,
|
|
media_type: str | None = None,
|
|
background: BackgroundTask | None = None,
|
|
) -> None:
|
|
"""初始化流式响应类
|
|
|
|
参数:
|
|
- data (Any): 响应数据。
|
|
- status_code (int): HTTP 状态码。
|
|
- headers (Mapping[str, str] | None): 响应头。
|
|
- media_type (str | None): 媒体类型。
|
|
- background (BackgroundTask | None): 后台任务。
|
|
|
|
返回:
|
|
- None
|
|
"""
|
|
# 位置参数传 content/status_code:业务代码不再出现 status_code 关键字传参
|
|
super().__init__(
|
|
data,
|
|
status_code,
|
|
media_type=media_type, # 文件类型
|
|
headers=headers, # 文件名
|
|
background=background, # 文件大小
|
|
)
|
|
|
|
|
|
class RedirectContentResponse(RedirectResponse):
|
|
"""重定向响应类"""
|
|
|
|
def __init__(
|
|
self,
|
|
url: str,
|
|
status_code: int = status.HTTP_302_FOUND,
|
|
headers: Mapping[str, str] | None = None,
|
|
) -> None:
|
|
"""初始化重定向响应类
|
|
|
|
参数:
|
|
- url (str): 重定向目标 URL。
|
|
- status_code (int): HTTP 状态码(默认 302)。
|
|
- headers (Mapping[str, str] | None): 响应头。
|
|
|
|
返回:
|
|
- None
|
|
"""
|
|
super().__init__(url, status_code, headers)
|
|
|
|
|
|
class UploadFileResponse(FileResponse):
|
|
"""文件响应
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
file_path: str,
|
|
filename: str,
|
|
media_type: str = "application/octet-stream",
|
|
headers: Mapping[str, str] | None = None,
|
|
background: BackgroundTask | None = None,
|
|
status_code: int = 200,
|
|
) -> None:
|
|
"""初始化文件响应类
|
|
|
|
参数:
|
|
- file_path (str): 文件路径。
|
|
- filename (str): 文件名。
|
|
- media_type (str): 文件类型。
|
|
- headers (Mapping[str, str] | None): 响应头。
|
|
- background (BackgroundTask | None): 后台任务。
|
|
- status_code (int): HTTP 状态码。
|
|
|
|
返回:
|
|
- None
|
|
"""
|
|
super().__init__(
|
|
file_path,
|
|
status_code,
|
|
headers=headers,
|
|
media_type=media_type,
|
|
background=background,
|
|
filename=filename,
|
|
stat_result=None,
|
|
method=None,
|
|
content_disposition_type="attachment",
|
|
)
|