有没有办法在 FastAPI 中为选定的请求参数生成请求模型?
Is there a way to generate request models for the selected request params in FastAPI?
我有一个枚举 class 用于存储一些这样的分类值。
class Fields(str, Enum):
text = "text"
para = "para"
images = "images"
并且每种类型都有华丽的模型。例如:
class imageModel(BaseModel):
min_width : int
max_height : int
is_exact : int
is_proportional : int
default_mode : int
default_quality : int
我有这样的字典:
type_attrs = {
"text": textModel,
"para": ParaModel,
"image": imageModel
}
我有一个 FastAPI 路由,用户需要在其中输入字段类型名称作为字符串(作为 fastapi 文档的下拉列表)并根据所选类型提供类型属性。
如果用户选择type = "images",则会提供相应的pydantic模型"ImageModel"供用户填写等。
请问有什么方法可以在选好类型名称后生成对应的pydantic模型吗?
谢谢。
您可以将 Union
或 List
与 response_model
一起使用
You can declare a response to be the Union of two types, that means, that the response would be any of the two.
和Union
from typing import Union
@app.get("/my_path", response_model=Union[FirstModel, SecondModel])
和List
from typing import List
@app.get("/my_path", response_model=List[FirstModel, SecondModel])
我不认为 FastAPI 可以支持这种类型的功能。基本上你要问的是基于 Fields 枚举输入的动态 swagger 模型渲染。我相信这需要挂钩到 swagger 页面。基本上整个 swagger 页面都是在 api 的运行时静态构建的。我建议您将 Fields 枚举分解为同一路径上的不同路径。
class imageModel(BaseModel):
min_width: int
max_height: int
is_exact: int
is_proportional: int
default_mode: int
default_quality: int
@app.post("/image")
def image(image: imageModel):
print(image)
return None
我有一个枚举 class 用于存储一些这样的分类值。
class Fields(str, Enum):
text = "text"
para = "para"
images = "images"
并且每种类型都有华丽的模型。例如:
class imageModel(BaseModel):
min_width : int
max_height : int
is_exact : int
is_proportional : int
default_mode : int
default_quality : int
我有这样的字典:
type_attrs = {
"text": textModel,
"para": ParaModel,
"image": imageModel
}
我有一个 FastAPI 路由,用户需要在其中输入字段类型名称作为字符串(作为 fastapi 文档的下拉列表)并根据所选类型提供类型属性。 如果用户选择type = "images",则会提供相应的pydantic模型"ImageModel"供用户填写等。
请问有什么方法可以在选好类型名称后生成对应的pydantic模型吗?
谢谢。
您可以将 Union
或 List
与 response_model
You can declare a response to be the Union of two types, that means, that the response would be any of the two.
和Union
from typing import Union
@app.get("/my_path", response_model=Union[FirstModel, SecondModel])
和List
from typing import List
@app.get("/my_path", response_model=List[FirstModel, SecondModel])
我不认为 FastAPI 可以支持这种类型的功能。基本上你要问的是基于 Fields 枚举输入的动态 swagger 模型渲染。我相信这需要挂钩到 swagger 页面。基本上整个 swagger 页面都是在 api 的运行时静态构建的。我建议您将 Fields 枚举分解为同一路径上的不同路径。
class imageModel(BaseModel):
min_width: int
max_height: int
is_exact: int
is_proportional: int
default_mode: int
default_quality: int
@app.post("/image")
def image(image: imageModel):
print(image)
return None