代码提交
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
"""统一响应包。
|
||||
|
||||
Success: {"code": 0, "msg": "ok", "data": ...}
|
||||
Failure: {"code": 404, "msg": "学生不存在", "data": null}
|
||||
code=0 表示成功,其余为业务错误码(与 HTTP 状态码对齐,前端可统一判断 code !== 0)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Generic, TypeVar
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class Resp(BaseModel, Generic[T]):
|
||||
code: int = Field(0, description="0=成功,非 0=业务错误码")
|
||||
msg: str = Field("ok", description="提示信息")
|
||||
data: T | None = Field(None, description="业务数据")
|
||||
|
||||
@classmethod
|
||||
def ok(cls, data: Any = None, msg: str = "ok") -> dict:
|
||||
return {"code": 0, "msg": msg, "data": data}
|
||||
|
||||
@classmethod
|
||||
def fail(cls, msg: str, code: int = 400, data: Any = None) -> dict:
|
||||
return {"code": code, "msg": msg, "data": data}
|
||||
|
||||
|
||||
def ok(data: Any = None, msg: str = "ok") -> dict:
|
||||
"""最常用的写法:return ok(result)"""
|
||||
return {"code": 0, "msg": msg, "data": data}
|
||||
Reference in New Issue
Block a user