函数创建内存中的zip文件并作为http响应返回

2024-04-26 17:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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够了吗?有更好的办法吗?

谢谢!


Tags: 文件closereadgetresponserequestdefcontent
2条回答

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

避免磁盘文件可能会使服务器慢到爬行,但它肯定会起作用。

如果同时处理太多这些请求,则会耗尽内存。

相关问题 更多 >