Python 基于Pydantic的FastApi动力学体

Python 基于Pydantic的FastApi动力学体,python,fastapi,pydantic,Python,Fastapi,Pydantic,我希望在FastApi上有一个动态的强制主体 我解释: from fastapi import FastAPI, Body from pydantic import BaseModel app = FastAPI() class Parameters(BaseModel): platform: str country: str @app.put("/myroute") async def provision_instance(*, parameters: Parameter

我希望在FastApi上有一个动态的强制主体

我解释:

from fastapi import FastAPI, Body
from pydantic import BaseModel

app = FastAPI()

class Parameters(BaseModel):
    platform: str
    country: str

@app.put("/myroute")
async def provision_instance(*, parameters: Parameters = Body(...)):
    do_something

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=80)
在这里,我的身体是在Parameters类中手动定义的,有两个属性,即platform和country。 将来,这些属性将来自一个配置文件,并且将有两个以上的属性。所以我需要动态地自动创建它们

例如,在配置文件中,我可以:

---
parameters:
  application:
    description: "Name of the application"
    type: string
  platform:
    description: "Name of the platform"
    type: string
  country:
    description: "Name of the country"
    type: string

在这种情况下,我如何能在主体中获得所需的可变数量的参数?我是否应该找到一种方法来为我的参数类提供可变数量的属性?

Pydantic模型可以按照文档中的描述动态构建。您仍然需要实现一个函数来读取yaml文件并从中构建Pydantic模型


在Python文件中考虑几个PyDyType模型;这不等于有一个yaml文件来描述模型吗


如果您提出了动态构建Pydantic模型的计划,因为将有多个形状的数据进入,那么您还可以探索使用以下方法定义端点:


类参数1(基本模型):
站台:str
国家:str
类参数2(基本模型):
应用:str
国家:str
@app.put(“/myroute”)
async def provision_实例(*,参数:Union[Parameters1,Parameters2]=正文(…):
如果isinstance(参数,参数1):
过去时
elif isinstance(参数,参数2):
过去时

谢谢托马斯的回答。我真的需要使用yaml配置文件。你能举个例子,我可以用动态键建立一个Pydantic模型吗?