Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...