简体   繁体   English

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

[英]Accepting different datatypes using Pydantic and FastAPI

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.我有一个用例,我使用 pydantic 模型从前端应用程序到 FastAPI backedn 接受不同数据类型的数据 - 即dict, boolean, string, int, list

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

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:在 python 3.9 以后,你不再需要 Union 了:

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.无论如何,我几乎找不到一个用例,使用 pydantic 的重点是强加数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM