Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

python - Is there a way to generate request models for the selected request params in FastAPI?

I have an enum class for storing some categorical values like this.

class Fields(str, Enum):
    text   = "text"
    para   = "para"
    images = "images"

And there are pydantic models for each of these types. For example:

class imageModel(BaseModel):
    min_width       : int
    max_height      : int
    is_exact        : int
    is_proportional : int
    default_mode    : int
    default_quality : int

And I have a dict like this:

type_attrs = {
    "text": textModel,
    "para": ParaModel,
    "image": imageModel
}

I have a FastAPI route where the user needs to input the Field type name as string (taken as dropdown from fastapi docs) and supply the type attributes according to the type chosen. If the user selects type = "images", the corresponding pydantic model "ImageModel" would be provided for thr user to fill in and so on.

Is there any way the corresponding pydantic model can be produced after selecting the type name?

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Union or List with your response_model

From the documentation:

You can declare a response to be the Union of two types, that means, that the response would be any of the two.

With Union

from typing import Union

@app.get("/my_path", response_model=Union[FirstModel, SecondModel])

With List

from typing import List

@app.get("/my_path", response_model=List[FirstModel, SecondModel])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...