请求格式以在FastAPI中上传多个图像

时间:2020-10-23 06:06:47

标签: python python-requests fastapi

示例

这是我的代码尝试上载图像列表:

import requests
import glob
import cv2

path = glob.glob("test_folder/*", recursive=True) # a list of image's path

lst_img = []
for p in path[:3]:
    # img = cv2.imread(p)
    lst_img.append((p, open(p, 'rb'), "image/jpeg"))

data = {"files": lst_img}

url = "http://localhost:6789/" # url api of app

res = requests.post(url=url, data=data)

print(res.status_code)

print(res.text)

说明

我正在尝试通过url api上传图像列表。在这里,我使用请求(python程序包),但也许我的请求格式不正确,那么我无法发布到url api。我收到错误代码422:

"detail":[{"loc":["body","files",0],"msg":"Expected UploadFile, received: <class 'str'>","type":"value_error"}

这是我的请求格式:

{'files': [('test_folder/image77.jpeg', <_io.BufferedReader name='test_folder/image77.jpeg'>, 'image/jpeg'), ('test_folder/image84.jpeg', <_io.BufferedReader name='test_folder/image84.jpeg'>, 'image/jpeg'), ('test_folder/image82.jpeg', <_io.BufferedReader name='test_folder/image82.jpeg'>, 'image/jpeg')]}

我尝试了很多方法,但总是失败。非常感谢你们帮助解决这个问题。

环境

  • 操作系统:Linux:(Ubuntu 18.04)
  • FastAPI版本:0.61.1
  • 请求版本:2.24.0
  • Python版本:3.7.5

我尝试过但仍然无法正常工作

lst_img.append(("file", (p, open(p, 'rb'), "image/jpeg")))

我的FastAPI main.py

from typing import List

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import StreamingResponse, FileResponse

app = FastAPI()

@app.post("/")
async def main(files: List[UploadFile] = File(...)):
    # file_like = open(video_path, mode="rb")
    # return StreamingResponse(file_like, media_type="video/mp4")
    return {"filenames": [file.filename for file in files]}

1 个答案:

答案 0 :(得分:0)

您应该使用files模块的request参数发送文件

import requests
import glob

path = glob.glob("test_folder/*", recursive=True) # a list of image's path

lst_img = []
for p in path[:3]:
    lst_img.append({"files": open(p, 'rb')})

url = "http://localhost:6789/" # url api of app

for data in lst_img:
    res = requests.post(url=url, files=data)
    print(res.status_code)
    print(res.text)