gpt4 book ai didi

python - Starlette JSONResponse 到 Pydantic parse_obj_as

转载 作者:行者123 更新时间:2023-12-05 03:42:07 26 4
gpt4 key购买 nike

使用 fastapi 并具有返回创建的 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()

这是返回值:

detail='Model 0 created' HTTPStatusCode=200

关于python - Starlette JSONResponse 到 Pydantic parse_obj_as,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67381171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com