python - 如何在aiohttp中发回图像/文件

标签 python python-3.x aiohttp

我需要知道如何在 aiohttp 中发回图像。我编写了一个用于调整图像大小的服务器。我使用了 aiohttp.web.FileResponse,但它需要保存文件,这有点问题(很多文件需要保存在硬盘上)。

有没有办法灵活地做到这一点(不保存文件)?可能来自图像字节之类的?我阅读了 aiohttp 文档,但没有做太多。

这是我尝试做的:

  1. 文件响应

这里我必须保存它以发送回响应

image = tasks.get(key)  # PIL.Image
image.save('im_server/pil_{}.jpg'.format(key))  
resp = web.FileResponse(f'im_server/pil_{key}.jpg')
return resp
  1. 流响应

当我使用此代码发出请求时,我得到了文件(正在上传到我的计算机上),但它不是图像。如果我尝试打开它作为图像,它说文件已损坏并且无法打开:(

image = tasks.get(key)  # PIL.Image
resp = web.StreamResponse(status=200)
resp.headers['Content-Type'] = 'Image/JPG'
await resp.prepare(request)
await resp.write(image.tobytes())
return resp

最佳答案

您可以使用 tempfile.SpooledTemporaryFile 来完成保存工作。它旨在将临时文件存储在内存中,并且只有在文件大小超过 max_size 参数时才会将文件保存在磁盘上。请注意,此参数默认为 0,因此您需要将其更改为合适的大小以避免将所有内容都存储在磁盘上。用法非常简单,SpooledTemporaryFile 将返回一个类似 file_like 的对象句柄,您可以像写入普通文件一样写入它。一旦不需要它,只需关闭它,它就会自动从内存或磁盘中删除。更多用法可以引用文档:https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile .

关于python - 如何在aiohttp中发回图像/文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62552345/

相关文章:

python - python aiohttp socketio 中是否可能存在竞争条件?

python - 类型错误 : '_IncompatibleKeys' object is not callable

python - 如何完全改变 tkinter.ttk Treeview 的背景颜色

python - 是否可以在一条指令中更改所有行值?

Python嵌套循环迭代列表中的列表

python - asyncio aiohttp 取消http请求轮询,返回结果

python - django - 验证 - 缺少所需的潜在参数 'self'

python - 根据其他行中其他列的匹配值更新列的 NULL 填充行

python - Facebook JSON 编码错误

python - 如何正确使用 asyncio.FIRST_COMPLETED