【问题标题】:passing dict value to BaseModel via Postman and OpenAPI in FastAPI在 FastAPI 中通过 Postman 和 OpenAPI 将 dict 值传递给 BaseModel
【发布时间】:2021-04-30 18:50:16
【问题描述】:

我对这个问题感到沮丧,我用谷歌搜索了它,但没有找到正确的答案,所以决定在这里问它。我有以下课程

from fastapi import FastAPI, File, UploadFile, BackgroundTasks, Body
from pydantic import BaseModel
import shutil
import datetime

class UserIn(BaseModel):
    username: str
    password: str
    family: str
    age: int
    height: float
    gender: bool

usr = UserIn(username='Bob', password='123456', family='Foo', age=21, height=169, gender=True)

还有下面的路由方法

@app.post("/uploadfile/")
async def create_upload_file(background_tasks: BackgroundTasks, current_user: UserIn = Body(usr),
                         file: UploadFile = File(...)):
    background_tasks.add_task(send_video_for_process, file, current_user)
    return {"message": f"The {current_user.username} file {file.filename} uploaded"}

功能是

def send_video_for_process(video: UploadFile, user: UserIn):
    content = video.file
    video_path = '/users/'
    path = video_path + user.username + video.filename
    with open(path, "wb") as buffer:
        shutil.copyfileobj(content, buffer) 
    return 'Done!'

当我没有传递任何东西时,该方法会正确传递usr,但是当我想通过邮递员或 Fastapi 的 \docs 传递它时。我收到以下错误。

{
"detail": [
    {
        "loc": [
            "body",
            "current_user"
        ],
        "msg": "value is not a valid dict",
        "type": "type_error.dict"
    }
]}

我在邮递员里放的字典是这个{"username": "Alice","password": "abcd1234","family": "Hey","age": 19,"height": 160,"gender": False}

这是我邮递员的截图。

在 /docs 中,我只更改了架构内的值,但仍然出现相同的错误。

我已经添加了所有库,我尝试不使用Body(...) 版本。我用字典玩了很多,但我一无所获。 我不想使用FormQuery。我将来需要 BaseModel 的好处。

我使用 Mac,我的服务器是 uvicorn

知道发生了什么吗?

【问题讨论】:

    标签: python postman fastapi pydantic


    【解决方案1】:

    两件事。

    1. Postman 屏幕截图显示您正在对正文使用表单数据编码,这与需要 json 的路径操作函数定义相混淆。您应该使用 'raw' 直接发送 json 数据。

    2. 您使用了False,正文中带有大写的'F',这是Python语言,不符合json(需要写false),这可能是OpenAPI错误的其余原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2016-01-11
      相关资源
      最近更新 更多