aeecleclair / Hyperion

API for ÉCLAIR's platform
https://myecl.fr
MIT License
16 stars 6 forks source link

Use a decorator to create a schema that should be used as a Form #284

Open armanddidierjean opened 1 year ago

armanddidierjean commented 1 year ago

Subject of the issue

A possible amelioration would be the usage of a as_form decorator to mark a schema as Form. See https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi/77113651#77113651

We would need to require Python 3.11 to use this syntax

import inspect
from typing import Annotated

from fastapi import Form

def as_form(cls):
    """
    https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi/77113651#77113651
    """
    new_params = [
        inspect.Parameter(
            field_name,
            inspect.Parameter.POSITIONAL_ONLY,
            default=model_field.default,
            annotation=Annotated[model_field.annotation, *model_field.metadata, Form()],
        )
        for field_name, model_field in cls.model_fields.items()
    ]

    cls.__signature__ = cls.__signature__.replace(parameters=new_params)

    return cls
armanddidierjean commented 2 months ago

https://fastapi.tiangolo.com/tutorial/request-form-models/