Files
DjangoAdmin_FastAPI_EleVue/core/response.py
T
ClaudeandClaude db4ee85db5 feat(phase1): core/ 基础设施迁移,旧路径改垫片
- core/: database/redis_client/jwt/password/response/exceptions/security/logger/deps/middleware/app
- create_app 迁移到 core/app.py,中间件注册顺序与异常处理器原样保留
- extensions/ utils/ apps/ 旧文件全部改为 re-export 垫片,import 路径保持兼容
- 新增 core 单元测试(jwt/password/response/request 共 12 个)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-07 10:02:01 +08:00

85 lines
2.3 KiB
Python

# +======================================================================
# | DjangoAdmin 企业数字化开发平台 [ 赋能开发者,助力企业发展 ]
# +----------------------------------------------------------------------
# | Copyright (c) 2021-2026 一米阳光团队 版权所有
# | 开源协议: Apache-2.0
# +======================================================================
# 由 utils/response.py 迁移而来。
"""统一响应结果模块:所有 API 返回 {code, data, msg, ok} 标准格式。"""
from typing import Any, Optional, Dict
from starlette.responses import JSONResponse
# 默认提示消息(避免从 apps.constants 循环导入)
MESSAGE_OK = "操作成功"
MESSAGE_FAIL = "操作失败"
def ok(
data: Optional[Any] = None,
msg: str = MESSAGE_OK,
code: int = 0,
**kwargs: Any
) -> JSONResponse:
"""生成成功响应,支持通过 kwargs 添加额外字段(如 count)。"""
response_body: Dict[str, Any] = {
"code": code,
"data": data,
"msg": msg,
"ok": True
}
if kwargs:
response_body.update(kwargs)
return JSONResponse(response_body)
def failed(
msg: str = MESSAGE_FAIL,
code: int = 1,
data: Optional[Any] = None,
**kwargs: Any
) -> JSONResponse:
"""生成失败响应。"""
response_body: Dict[str, Any] = {
"code": code,
"data": data,
"msg": msg,
"ok": False
}
if kwargs:
response_body.update(kwargs)
return JSONResponse(response_body)
def response(
data: Optional[Any] = None,
msg: str = MESSAGE_OK,
code: int = 0,
success: bool = True,
**kwargs: Any
) -> JSONResponse:
"""通用响应生成器(高级用法),允许完全自定义字段。"""
response_body: Dict[str, Any] = {
"code": code,
"data": data,
"msg": msg,
"ok": success
}
if kwargs:
response_body.update(kwargs)
return JSONResponse(response_body)
# 常用错误码常量
class Codes:
"""常用状态码定义"""
SUCCESS = 0
FAILED = 1
UNAUTHORIZED = 401 # 未认证
FORBIDDEN = 403 # 无权限
NOT_FOUND = 404 # 资源不存在
VALIDATE_ERROR = 422 # 验证错误
SERVER_ERROR = 500 # 服务器错误