如何使用Python请求在FastAPI中上传多张图片?

问题描述 投票:0回答:2

示例

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

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)

描述

我正在尝试通过Python请求(包)将图像列表上传到FastAPI端点,但也许我的请求格式错误,导致

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]}
python file-upload python-requests fastapi
2个回答
5
投票

下面是如何使用Python请求和FastAPI上传多个文件(图像)的示例。如果您在上传文件时需要发送额外的数据,请查看这里。另外,如果您需要

async
阅读,以及写作以将图像保存在服务器端,请查看这个答案

app.py

from fastapi import FastAPI, File, UploadFile, HTTPException, status
from typing import List

app = FastAPI()

@app.post("/upload")
def upload(files: List[UploadFile] = File(...)):
    for file in files:
        try:
            contents = file.file.read()
            with open(file.filename, 'wb') as f:
                f.write(contents)
        except Exception:
            raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, 
                detail='There was an error uploading the file')
        finally:
            file.file.close()

    return {"message": f"Successfuly uploaded {[file.filename for file in files]}"}    

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=8000)

测试.py

import requests
import glob

paths = glob.glob("images/*", recursive=True) # returns a list of file paths
images = [('files', open(p, 'rb')) for p in paths] # or paths[:3] to select the first 3 images
url = 'http://127.0.0.1:8000/upload'
resp = requests.post(url=url, files=images) 
print(resp.json())

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)

© www.soinside.com 2019 - 2024. All rights reserved.