简体   繁体   中英

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.

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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