fastapi表单数据与pytantic模型

fastapi表单数据与pytantic模型,第1张

fastapi表单数据与pytantic模型

我找到了一个可以帮助我们将FastAPI表单也用作pydantic的解决方案:)
我的代码:

class AnyForm(baseModel):    any_param: str    any_other_param: int = 1    @classmethod    def as_form(        cls,        any_param: str = Form(...),        any_other_param: int = Form(1)    ) -> AnyForm:        return cls(any_param=any_param, any_other_param=any_other_param)@router.post('')async def any_view(form_data: AnyForm = Depends(AnyForm.as_form)):        ...

它以
我通常认为的形式大张旗鼓地显示,可以写得更通用,也许我会返回并编辑答案。

[更新]

我已经把它写成装饰器了

import inspectfrom typing import Typefrom fastapi import Formfrom pydantic import baseModelfrom pydantic.fields import ModelFielddef as_form(cls: Type[baseModel]):    new_parameters = []    for field_name, model_field in cls.__fields__.items():        model_field: ModelField  # type: ignore        if not model_field.required: new_parameters.append(     inspect.Parameter(         model_field.alias,         inspect.Parameter.POSITIONAL_ONLY,         default=Form(model_field.default),         annotation=model_field.outer_type_,     ) )        else: new_parameters.append(     inspect.Parameter(         model_field.alias,         inspect.Parameter.POSITIONAL_ONLY,         default=Form(...),         annotation=model_field.outer_type_,     ) )    async def as_form_func(**data):        return cls(**data)    sig = inspect.signature(as_form_func)    sig = sig.replace(parameters=new_parameters)    as_form_func.__signature__ = sig  # type: ignore    setattr(cls, 'as_form', as_form_func)    return cls

用法看起来像

class Test1(baseModel):    a: str    b: int@as_formclass Test(baseModel):    param: str    test: List[Test1]    test1: Test1    b: int = 1    a: str = '2342'@router.post('/me', response_model=Test)async def me(request: Request, form: Test = Depends(Test.as_form)):    return form


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5647955.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存