通过 Python 请求发送 PIL 图像

时间:2021-03-12 18:04:26

标签: python image python-requests save python-imaging-library

我需要创建一个图像并将其保存在数据库中。我正在使用 python Pillow 创建它并将其保存为 JPEG。

image = Process().mandelbrot(width, height, max_iter)

mem_file = BytesIO()
image.save(mem_file, "JPEG", quality=100)
mem_file.seek(0)

创建后,我试图通过python-requests将其保存在数据库中

form_data = {'image': ('mandelbrot'+str(uuid.uuid4().hex), mem_file)}
requests.post(url='http://database:5000/images', files=form_data)

我正在尝试发送表单数据请求,但是当我检查数据库中的数据时,未找到该文件且其值为无

ImmutableMultiDict([('image', <FileStorage: 'mandelbrot8a9275e838a04a0f94b731c47bc6bdd4' (None)>)])

有谁知道如何发送 PIL 文件并使用 form-data mimetype 抛出 python 请求而不获取具有 None 值的文件?

1 个答案:

答案 0 :(得分:0)

正如@mugiseyebrows 所说我做错了,表单数据应该如下

form_data= {"image": ("image.jpeg", mem_file, "image/jpeg")}

通过这种方式发送 mime 类型,我能够使用表单数据请求发送我的图像抛出 python 请求

孔码变成以下

image = Process().mandelbrot(width, height, max_iter)

mem_file = BytesIO()
image.save(mem_file, "PNG", quality=100)
mem_file.seek(0)
        
id = 'mandelbrot'+str(uuid.uuid4().hex)

requests.post(url='http://database:5000/images', files={'image': ('file.PNG', mem_file, 'image/png')}, params={'id': id})