# +====================================================================== # | 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 # 服务器错误