使用pydantic和fastapi接受不同的数据类型

发布于 2025-01-30 03:15:55 字数 461 浏览 2 评论 0原文

我有一个用例,即我接受不同数据类型的数据 - 即dict,boolean,string,int,list,list - 使用Pydantic模型从前端应用程序到FastApi Backedn。

我的问题是我应该如何设计我的pydantic模型,以便它可以接受任何数据类型,后来可以用于操纵数据并创建API?

from pydantic import BaseModel

class Pino(BaseModel):
    asset:str (The data is coming from the front end ((dict,boolean,string,int,list))  )

@app.post("/api/setAsset")
async def pino_kafka(item: Pino):
    messages = {
        "asset": item.asset
}

I have a use case where I am accepting data of different datatypes - namely dict, boolean, string, int, list - from the front end application to the FastAPI backedn using a pydantic model.

My question is how should I design my pydantic model so that it can accept any data type, which can later be used for manipulating the data and creating an API?

from pydantic import BaseModel

class Pino(BaseModel):
    asset:str (The data is coming from the front end ((dict,boolean,string,int,list))  )

@app.post("/api/setAsset")
async def pino_kafka(item: Pino):
    messages = {
        "asset": item.asset
}

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

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

发布评论

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

评论(1

比忠 2025-02-06 03:15:55

定义自定义数据类型:

from typing import Optional, Union
my_datatype = Union[dict,boolean,string,int,list]

您不需要联合

my_datatype = dict | boolean | string | int | list

python 3.9中,

class Pino(BaseModel):
    asset: my_datatype

from typing import Any
class Pino(BaseModel):
    asset: Any

在 为此,使用Pydantic的全部要点是施加数据类型。

Define a custom datatype:

from typing import Optional, Union
my_datatype = Union[dict,boolean,string,int,list]

In python 3.9 onwards, you don't need Union any-more:

my_datatype = dict | boolean | string | int | list

Then use it in your model:

class Pino(BaseModel):
    asset: my_datatype

If you really want "any" datatype, just use "Any":

from typing import Any
class Pino(BaseModel):
    asset: Any

In any case, I hardly find a use case for this, the whole point of using pydantic is imposing datatypes.

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