小编dia*_*sis的帖子

为什么使用 FastAPI 上传图像时会收到“无法处理的实体”错误?

我正在尝试上传图像,但 FastAPI 返回时出现一个我无法弄清楚的错误。

file: UploadFile = File(...)如果我从函数定义中省略“ ”,它就会正常工作。但是当我将 the 添加file到函数定义中时,它会抛出错误。

这是完整的代码。

@router.post('/', response_model=schemas.PostItem, status_code=status.HTTP_201_CREATED)
def create(request: schemas.Item, file: UploadFile = File(...), db: Session = Depends(get_db)):

    new_item = models.Item(
        name=request.name,
        price=request.price,
        user_id=1,
    )
    print(file.filename)
    db.add(new_item)
    db.commit()
    db.refresh(new_item)
    return new_item
Run Code Online (Sandbox Code Playgroud)

Pydantic模型Item只是

class Item(BaseModel):
    name: str
    price: float
Run Code Online (Sandbox Code Playgroud)

错误是:
代码 422 错误:无法处理的实体

{
  "detail": [
    {
      "loc": [
        "body",
        "request",
        "name"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "body",
        "request",
        "price"
      ],
      "msg": "field required", …
Run Code Online (Sandbox Code Playgroud)

python python-3.x fastapi

5
推荐指数
1
解决办法
5126
查看次数

标签 统计

fastapi ×1

python ×1

python-3.x ×1