Python/Django:提供 zip 文件以从 io.BytesIO 缓冲区下载

Rob*_*ski 0 python django

我正在尝试将 zip 文件放入 io.BytesIO 缓冲区中,然后提供下载。下面是我得到的内容(较长的views.py的一部分,我只是发布相关部分)。

但我收到以下错误消息:

AttributeError at 'bytes' object has no attribute 'read'
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么?

from django.http import HttpResponse
from wsgiref.util import FileWrapper
from zipfile import *
import io

buffer = io.BytesIO()

zipf = ZipFile(buffer, "w")
zipf.write ("file.txt")
zipf.close()

response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=file.zip'

return response
Run Code Online (Sandbox Code Playgroud)

编辑:它告诉我错误来自以下行:

response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
Run Code Online (Sandbox Code Playgroud)

小智 5

我知道这个线程有点旧,但仍然如此。

BytesIO 对象的方法返回可以传递给withgetvalue()的字节内容。HttpResponsecontent_type='application/zip'

buffer = io.BytesIO()
zipf = ZipFile(buffer, "w")
zipf.write ("file.txt")
zipf.close()
response = HttpResponse(buffer.getvalue(), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=file.zip'
return response
Run Code Online (Sandbox Code Playgroud)