请求在FastAPI中上传多张图片的格式 [英] Requests format for uploading multiple images in FastAPI
本文介绍了请求在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]}
推荐答案
下面是一个使用PYTHON请求和FastAPI上传多个文件(图片)的示例。如果您在上传文件时需要发送额外数据,请查看here。另外,如果您需要async
编写保存服务器端的图片,请查看this answer。
app.py
import uvicorn
from fastapi import File, UploadFile, FastAPI
from typing import List
app = FastAPI()
def save_file(filename, data):
with open(filename, 'wb') as f:
f.write(data)
@app.post("/upload")
async def upload(files: List[UploadFile] = File(...)):
# in case you need the files saved, once they are uploaded
for file in files:
contents = await file.read()
save_file(file.filename, contents)
return {"Uploaded Files": [file.filename for file in files]}
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000)
test.py
import requests
import glob
path = glob.glob("images/*", recursive=True) # images' path
images = [('files', open(p, 'rb')) for p in path] # or path[:3] to upload the first 3 images
url = 'http://127.0.0.1:8000/upload'
resp = requests.post(url=url, files=images)
print(resp.json())
这篇关于请求在FastAPI中上传多张图片的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文