创建内存中 zip 文件并作为 http 响应返回的函数
我避免在磁盘上创建文件,这就是我到目前为止所得到的:
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
您认为正确-优雅-Pythonic足够了吗?有更好的方法吗?
谢谢!
I am avoiding the creation of files on disk, this is what I have got so far:
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
Do you think is correct-elegant-pythonic enough? Any better way to do it?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于
StringIO
,您通常应该使用o.getvalue()
来获取结果。另外,如果您想将普通文件添加到 zip 文件中,可以使用zf.write('picture.jpg')
。您不需要手动阅读它。For
StringIO
you should generally useo.getvalue()
to get the result. Also, if you want to add a normal file to the zip file, you can usezf.write('picture.jpg')
. You don't need to manually read it.避免使用磁盘文件可能会降低服务器速度,但它肯定会起作用。
如果同时处理太多此类请求,您将耗尽内存。
Avoiding disk files can slow your server to a crawl, but it will certainly work.
You'll exhaust memory if you serve too many of these requests concurrently.