python - 如何使用邮递员将文件发送到 fastapi 端点
问题描述
我遇到了使用邮递员测试 api 的困难。通过 swagger 文件上传功能正常工作,我在硬盘上保存了一个文件。我想了解如何与邮递员一起执行此操作。我使用标准方式来处理我在使用 Django、flask 时使用的文件。
Body -> form-data: key=file, value=image.jpeg
但是使用快速 API,我得到一个错误
127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity
主文件
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
img = await file.read()
if file.content_type not in ['image/jpeg', 'image/png']:
raise HTTPException(status_code=406, detail="Please upload only .jpeg files")
async with aiofiles.open(f"{file.filename}", "wb") as f:
await f.write(img)
return {"filename": file.filename}
我也试过了body -> binary: image.jpeg
。但得到了相同的结果
解决方案
我的代码:
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/file/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
如https://github.com/tiangolo/fastapi/issues/1653中所述,文件的参数名称是您必须使用的键值。在您使用 key=file 和 value=image.png (或其他)之前。相反,FastAPI 接受 file=image.png。因此错误,因为该文件是必需的,但它不存在(至少,具有该名称的键不存在)。
PS 我用 Postman v7.16.1 测试过
推荐阅读
- reactjs - 反应无限循环 axios.all
- java - 我应该如何扩展 com.microsoft.azure.spring.autoconfigure.aad.UserPrincipal?
- reactjs - 与表单一起提交后,我应该如何显示可编辑数据,以便我可以重用表单组件?
- php - PHP mysql_xdevapi 扩展:replaceOne() 似乎不是幂等的
- .net-core - 如何从 dotnet watch run 中排除某些文件类型?
- javascript - 改变高度后保持图像中心
- c - 为什么我不能只得到矩阵中元素的第一次出现?
- sql - 有没有办法在 SQL 中只搜索月份和日期?
- reactjs - 反应原生
到 UI 前面 - javascript - 从对象数组制作树,保留其他键值对