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

question from:https://stackoverflow.com/questions/65833973/is-there-a-way-to-generate-request-models-for-the-selected-request-params-in-fas

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

1 Reply

0 votes
by (71.8m points)

I don't think FastAPI can support this type of functionality. Basically what you are asking is for dynamic swagger model rendering based on the input from the Fields enum. This would require a hook into the swagger page I believe. Basically the entire swagger page is built statically at runtime of the api. I would suggest you break the Fields enum into separate paths on the same route.

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

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

...