Starlette JSONResponse 到 Pydantic parse_obj_as

Starlette JSONResponse into Pydantic parse_obj_as

使用 fastapi 并具有 returns 创建 JSONResponse 的功能。我的目标是创建自定义 200 响应并使用预期的 BaseModel 将其放入 Pydantic parse_obj_as

有没有办法取回 JSONResponse 数据?或者有什么解决方法?谢谢!

from starlette.responses import JSONResponse


def func():
    model_id = 0

    resp = JSONResponse(
        {"detail": f"Model {model_id} created", "HTTPStatusCode": 200},
       status_code=200,
    )
    return parse_obj_as(<here I need resp data>, MyBaseModel)

基础模型:

from pydantic.types import PositiveInt
from __future__ import annotations, generator_stop
from pydantic import BaseModel

class MyBaseModel(BaseModel):
    """
    Docstring
    """

    detail: str
    HTTPStatusCode: PositiveInt

parse_obj_as 需要字典输入。响应对象的主体可通过 response.body 访问。并且您需要通过调用 json.loads().

将字节类型的正文转换为字典
import json
from pydantic.types import PositiveInt
from starlette.responses import JSONResponse
from pydantic import BaseModel, parse_obj_as


class MyBaseModel(BaseModel):
    """
    Docstring
    """
    detail: str
    HTTPStatusCode: PositiveInt


def func():
    model_id = 0
    resp = JSONResponse(
        {"detail": f"Model {model_id} created", "HTTPStatusCode": 200}, status_code=200,
    )
    return parse_obj_as(MyBaseModel, json.loads(resp.body))


ret = func()

这是 return 值:

detail='Model 0 created' HTTPStatusCode=200