在FastAPI中,我使用SQLAlChemy和PYDANIC返回数据.

@router.get("/1", response_model=User)
def read_user(db: Session = Depends(get_db)):
db_user = user_module.get_user(db, user_id="1")
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user

这种方法帮助我标准化了返回模型,但我希望将所有API的响应格式统一为{"code": 0, "msg": "success", "data": {...}},以便将原始返回模型中的用户模型放在"data"字段中,使其更易于前端管理.

我try 使用FastAPI中间件来实现,但它无法识别Swagger和其他文档中的用户返回模型.如果我使用嵌套模型重新定义通用的Pydtic返回模型,则无法将SQLAlChemy返回的数据模型操作为所需的用户模型.

有没有办法解决我的需求,或者有没有更好的解决方案?

将FastAPI中的响应格式统一到 {"code": 0, "msg": "success", "data": {...}},同时保留简单的数据模型,并确保在Swagger和其他文档中正确识别.

推荐答案

from pydantic import BaseModel, Field
from typing import Generic, TypeVar, Type, Optional
from fastapi import Depends, HTTPException, APIRouter
from sqlalchemy.orm import Session

T = TypeVar('T')

class GenericResponse(BaseModel, Generic[T]):
    code: int = Field(default=0, example=0)
    msg: str = Field(default="success", example="success")
    data: Optional[T]

router = APIRouter()

@router.get("/1", response_model=GenericResponse[User])
def read_user(db: Session = Depends(get_db)):
    db_user = user_module.get_user(db, user_id="1")
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return GenericResponse(data=db_user)

声明泛型响应或许能够帮助您修复 struct 并标准化所需类型的响应.

Python相关问答推荐

pyautogui.locateOnScreen在Linux上的工作方式有所不同

如何销毁框架并使其在tkinter中看起来像以前的样子?

根据网格和相机参数渲染深度

如何处理嵌套的SON?

无法使用equals_html从网址获取全文

Python:在类对象内的字典中更改所有键的索引,而不是仅更改一个键

Odoo 14 hr. emergency.public内的二进制字段

为什么这个带有List输入的简单numba函数这么慢

Python虚拟环境的轻量级使用

python中字符串的条件替换

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

如何指定列数据类型

python—telegraph—bot send_voice发送空文件

如何将数据帧中的timedelta转换为datetime

Cython无法识别Numpy类型

比Pandas 更好的 Select

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

在Django中重命名我的表后,旧表中的项目不会被移动或删除

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

如何为需要初始化的具体类实现依赖反转和接口分离?