使用pydantic和fastapi接受不同的数据类型
我有一个用例,即我接受不同数据类型的数据 - 即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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
定义自定义数据类型:
您不需要联合
python 3.9中,
。
在 为此,使用Pydantic的全部要点是施加数据类型。
Define a custom datatype:
In python 3.9 onwards, you don't need Union any-more:
Then use it in your model:
If you really want "any" datatype, just use "Any":
In any case, I hardly find a use case for this, the whole point of using pydantic is imposing datatypes.