Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
armanddidierjean opened this issue Nov 6, 2023 · 0 comments
Open
Labels
core question Further information is requested

Comments

@armanddidierjean
Copy link
Member

armanddidierjean commented Nov 6, 2023

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 armanddidierjean added question Further information is requested core labels Nov 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
core question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant