Skip to content

数据统一返回格式 ​

app/interfaces/schemas ​

  • 新建base.py
python
# 引入泛型
from typing import TypeVar,Generic,Optional

# 引入基础模型
from pydantic import BaseModel,Field

# 定义泛型参数
T = TypeVar("T")

# 定义响应模型
class Response(BaseModel,Generic[T]):
  """基础API响应结构.继承BaseModel,并定义泛型
  """
  code:int = 200 # 业务状态码.和HTTP状态码一致
  msg:str = "success" # 响应消息.提示
  data:Optional[T] = Field(default_factory=dict) # 响应数据为空字典

  @staticmethod
  def success(data:Optional[T] = None,msg:str="success") -> "Response[T]":
    """成功响应.返回成功状态码和数据
    """
    return Response(code=200,msg=msg,data=data if data is not None else {})

  @staticmethod
  def fail(code:int,msg:str,data:Optional[T] = None) -> "Response[T]":
    """失败消息提示,携带code和msg
    """
    return Response(code=code,msg=msg,data=data if data is not None else {})