创建内存中的zip文件并作为http响应返回的功能 [英] Function to create in-memory zip file and return as http response

查看:216
本文介绍了创建内存中的zip文件并作为http响应返回的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在避免在磁盘上创建文件,这是我到目前为止所获得的:

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

您认为正确优雅的Python语言够用吗?还有更好的方法吗?

Do you think is correct-elegant-pythonic enough? Any better way to do it?

谢谢!

推荐答案

对于StringIO,通常应使用o.getvalue()来获取结果.另外,如果要将普通文件添加到zip文件中,则可以使用zf.write('picture.jpg').您不需要手动阅读它.

For StringIO you should generally use o.getvalue() to get the result. Also, if you want to add a normal file to the zip file, you can use zf.write('picture.jpg'). You don't need to manually read it.

这篇关于创建内存中的zip文件并作为http响应返回的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆