使用Pydantic和FastAPI接受不同的数据类型



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

我的问题是我应该如何设计我的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
}

定义自定义数据类型:

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

在python 3.9以后,你不再需要Union了:

my_datatype = dict | boolean | string | int | list

然后在你的模型中使用它:

class Pino(BaseModel):
asset: my_datatype

如果你真的想要"any"数据类型,只需使用"Any":

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

在任何情况下,我几乎找不到这样的用例,使用pydantic的全部意义是强加数据类型。

最新更新