pydantic在fastapi中序列化

发布于 2025-01-29 01:50:19 字数 325 浏览 2 评论 0 原文

sqlalchemy in Sqlalchemy

我会分别问这个问题,但内容不同。
我想序列化连接,然后与pydantic序列化,但它不起作用。
如果可能的话,我想将其返回,就像它是一个对象一样。

{
 id: 1,
 parent_column: test1,
 child_column: test2
}

Relation in sqlalchemy

I'll ask this question separately, since it's a continuation of this one, but with a different content.
I want to serialize a join and then serialize it with pydantic, but it doesn't work.
If possible, I want to return it as if it were a single object.

{
 id: 1,
 parent_column: test1,
 child_column: test2
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魔法少女 2025-02-05 01:50:19

您可以使用所需的信息创建一个Pydantic模型,因此该模型将负责序列化为JSON格式。

from pydantic import BaseModel

class MyResponse(BaseModel):
    id: int
    parent: str
    child: str

您只需要通过以请求的格式提供数据来创建模型的响应。


data_json = MyResponse(id= my_data.id, parent=my_data.parent, child=my_data.child)

以下是一个带有FastAPI端点的示例,该示例将使用ID检索特定数据并使用特定模板返回JSON响应。

from pydantic import BaseModel
from fastapi import status

class MyResponse(BaseModel):
    id: int
    parent: str
    child: str


@ router.get('/data',
             status_code=status.HTTP_200_OK,
             response_model=MyResponse)
def get_data(parent_id:int):
    try:
        data = get_data(parent_id)
    except Exception:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail="Server Error")

    return MyResponse(id=data.id, parent=data.parent, child=data.child)

之后,可以通过pydantic类的 orm_mode 将Pydantic模型与SQLalchemy联系起来。更多信息在这里:

You can create a Pydantic model with the information you want, so the model will take care of the serialization to JSON format.

from pydantic import BaseModel

class MyResponse(BaseModel):
    id: int
    parent: str
    child: str

You just have to create a response from your model by providing it with the data in the requested format.


data_json = MyResponse(id= my_data.id, parent=my_data.parent, child=my_data.child)

Below is an example given with a fastAPI endpoint that would take an ID to retrieve a specific data and return a JSON response with a specific template.

from pydantic import BaseModel
from fastapi import status

class MyResponse(BaseModel):
    id: int
    parent: str
    child: str


@ router.get('/data',
             status_code=status.HTTP_200_OK,
             response_model=MyResponse)
def get_data(parent_id:int):
    try:
        data = get_data(parent_id)
    except Exception:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail="Server Error")

    return MyResponse(id=data.id, parent=data.parent, child=data.child)

Afterwards, it is possible to link Pydantic models with sqlalchemy via the orm_mode of the Pydantic class. More information here: https://fastapi.tiangolo.com/tutorial/sql-databases/#use-pydantics-orm_mode

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文