【发布时间】: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(...) 版本。我用字典玩了很多,但我一无所获。
我不想使用Form 或Query。我将来需要 BaseModel 的好处。
我使用 Mac,我的服务器是 uvicorn。
知道发生了什么吗?
【问题讨论】:
标签: python postman fastapi pydantic