wance_data/src/responses.py

47 lines
1.6 KiB
Python

import typing
from typing import Generic, Sequence, TypeVar
from fastapi import status
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel
T = TypeVar("T")
class BaseResponse(BaseModel, Generic[T]):
"""通用响应类"""
status_code: int
message: str
data: typing.Optional[T] = None
def json_response(self) -> JSONResponse:
"""返回 JSONResponse 响应"""
return JSONResponse(
status_code=self.status_code,
content=jsonable_encoder(self.dict())
)
def create_response(data: T = None, status_code: int = 200, message: str = "Success") -> JSONResponse:
"""通用响应函数"""
response = BaseResponse(status_code=status_code, message=message, data=data)
return response.json_response()
# 使用示例
def response_success(message: str = 'Success') -> JSONResponse:
return create_response(status_code=status.HTTP_200_OK, message=message)
def response_unauthorized(message: str = "用户认证失败") -> JSONResponse:
return create_response(status_code=status.HTTP_401_UNAUTHORIZED, message=message)
def response_entity_response(data: T, message: str = "Success") -> JSONResponse:
"""单个实体数据响应"""
return create_response(data=data, status_code=200, message=message)
def response_list_response(data: Sequence[T], message: str = "Success") -> JSONResponse:
"""列表数据响应"""
return create_response(data=data, status_code=200, message=message)