我避免在磁盘上创建文件,这是我目前所得到的:
def get_zip(request):
import zipfile, StringIO
i = open('picture.jpg', 'rb').read()
o = StringIO.StringIO()
zf = zipfile.ZipFile(o, mode='w')
zf.writestr('picture.jpg', i)
zf.close()
o.seek(0)
response = HttpResponse(o.read())
o.close()
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment; filename=\"picture.zip\""
return response
你认为 correct-elegant-pythonic 就足够了吗?有什么更好的方法吗?
谢谢!
最佳答案
对于 StringIO
,您通常应该使用 o.getvalue()
来获取结果。另外,如果要将普通文件添加到 zip 文件中,可以使用 zf.write('picture.jpg')
。您无需手动阅读。
关于python - 创建内存中 zip 文件并作为 http 响应返回的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411514/