Advertisement
NikolayGorshenin

Untitled

Oct 3rd, 2022
644
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. import inspect
  2. from typing import Type
  3.  
  4. from fastapi import Form
  5. from pydantic import BaseModel, Field
  6. from pydantic.fields import ModelField
  7.  
  8. def as_form(cls: Type[BaseModel]):
  9.     new_parameters = []
  10.  
  11.     for _, model_field in cls.__fields__.items():
  12.         model_field: ModelField  # type: ignore
  13.  
  14.         new_parameters.append(
  15.              inspect.Parameter(
  16.                  model_field.alias,
  17.                  inspect.Parameter.POSITIONAL_ONLY,
  18.                  default=Form(...) if model_field.required else Form(model_field.default),
  19.                  annotation=model_field.outer_type_,
  20.              )
  21.          )
  22.  
  23.     async def as_form_func(**data):
  24.         return cls(**data)
  25.  
  26.     sig = inspect.signature(as_form_func)
  27.     sig = sig.replace(parameters=new_parameters)
  28.     as_form_func.__signature__ = sig  # type: ignore
  29.     setattr(cls, 'as_form', as_form_func)
  30.     return cls
  31.  
  32.  
  33. @as_form
  34. class MyForm(BaseModel):
  35.     id: int
  36.     name: str
  37.     age: int = Field(default=10)
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement