如何使用 Python 请求将多个图像 POST 发送到 FastAPI 服务器?

How to POST multiple images to FastAPI server using Python requests?

我想使用 Python 个请求将多个图像发送到 FastAPI 后端。

服务器端

from fastapi import FastAPI, UploadFile, File
from typing import List
app = FastAPI()

@app.post("/")
def index(file: List[UploadFile] = File(...)):
    list_image = []
    for i in file:
        list_image.append(i.filename)
    return {"list_image": list_image}

客户端

目前只能发送单张图片请求。但是,我希望能够发送多张图片。

import requests
import cv2

frame = cv2.imread("../image/3.png")
imencoded = cv2.imencode(".jpg", frame)[1]
file = {'file': ('image.jpg', imencoded.tostring(),
                    'image/jpeg', {'Expires': '0'})}

response = requests.post("http://127.0.0.1:8000/", files=file)

使用如下:

import requests

url = 'http://127.0.0.1:8000/'
files = [('file', open('images/1.png', 'rb')), ('file', open('images/2.png', 'rb'))]
resp = requests.post(url=url, files=files) 

或者,您也可以使用:

import requests
import glob

path = glob.glob("images/*", recursive=True) # images' path
files = [('file', open(img, 'rb')) for img in path]
url = 'http://127.0.0.1:8000/'
resp = requests.post(url=url, files=files)