【问题标题】:Dynamical body in FastApi using Pydantic使用 Pydantic 的 FastApi 中的动态体
【发布时间】:2020-07-07 06:47:38
【问题描述】:

我希望在 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)

这里,我的body是在Parameters类中手动定义的,有两个属性,平台和国家。 未来,这些属性将来自一个配置文件,并且会有两个以上的属性。所以我需要动态地自动创建它们。

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

---
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

在这种情况下,我如何在正文中拥有可变数量的参数?我应该找到一种方法为我的参数类提供可变数量的属性吗?

【问题讨论】:

    标签: python fastapi pydantic


    【解决方案1】:

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


    现在考虑一个 python 文件中的几个 Pydantic 模型;这不等于拥有一个描述模型的 yaml 文件吗?


    如果您想出动态构建 Pydantic 模型的计划,因为您将收到多种形状的数据,您还可以探索使用 typing.Union 来定义您的端点:

    
    class Parameters1(BaseModel):
        platform: str
        country: str
    
    
    class Parameters2(BaseModel):
        application: str
        country: str
    
    
    @app.put("/myroute")
    async def provision_instance(*, parameters: Union[Parameters1, Parameters2] = Body(...)):
        if isinstance(parameters, Parameters1):
            pass  # TODO
        elif isinstance(parameters, Parameters2):
            pass  # TODO
    
    

    【讨论】:

    • 感谢托马斯的回答。我真的需要使用 yaml 配置文件。你有一个例子,我可以用动态键构建一个 Pydantic 模型吗?
    • 嘿@Nico 你能解决这个问题吗?
    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 2022-01-21
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2021-04-15
    • 2021-03-04
    相关资源
    最近更新 更多