【发布时间】:2022-12-08 08:14:40
【问题描述】:
我的 FastAPI 应用程序中有一个端点用于接收表单数据:
@router.post("/foobar")
async def handler(
form_data: Bar = Depends(Bar.as_form),
) -> JSONResponse:
...
我想做的是在pydantic 的帮助下验证表单数据。以下是模型:
from fastapi import Form
from pydantic import BaseModel, Json
class Foo(BaseModel):
a: str
class Bar(BaseModel):
any_field: Optional[List[Foo]]
@classmethod
def as_form(
cls,
any_field: Json[List[Foo]] = Form(None, media_type="application/json"),
) -> "Bar":
return cls(any_field=any_field)
但我收到以下错误:
fastapi.exceptions.RequestValidationError: 1 validation error for Request
body -> any_field
JSON object must be str, bytes or bytearray (type=type_error.json)
我已经为 RequestValidationError 添加了异常处理程序以确保 any_field 实际上是 str 类型:
@application.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
body: FormData = exc.body
return JSONResponse(
content={"msg": str([type(v) for v in body.values()])},
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY
)
如您所见,它是str。
为什么会出现这个错误?
【问题讨论】: