python - 在 Django 上创建临时 zip 文件并在返回后将其删除

标签 python django

我想将我的服务器上的许多文件打包并制作一个zip文件,让人们从我的网站下载,一旦人们下载,该文件就会被删除。

我在 stackoverflow 上搜索,找到了一些主题,但没有一个符合我的要求。

这是我的代码:

file_name = 'temp.zip'
temp_zip_file = zipfile.ZipFile(file_name, 'w')

...do something and get the files...

for file in files:
    temp_zip_file.write(name, arcname=name)

temp_zip_file.close()
response = HttpResponse(open(file_name, 'r').read(), mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s"' % file_name
return response

哪里可以添加删除代码并自动删除?

非常感谢。

最佳答案

您可以使用StringIO而不是真实的文件。 StringIO是一个类似文件的字符串缓冲区。

import zipfile
from cStringIO import StringIO

s = StringIO()
temp_zip_file = zipfile.ZipFile(s, 'w')
# ...
temp_zip_file.close()

print s.getvalue()

所以在你的情况下你应该这样做:

stream = StringIO()
temp_zip_file = zipfile.ZipFile(stream, 'w')

...do something and get the files...

for file in files:
    temp_zip_file.write(name, arcname=name)

temp_zip_file.close()
response = HttpResponse(stream.getvalue(), mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename="temp.zip"'
return response

关于python - 在 Django 上创建临时 zip 文件并在返回后将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28316787/

相关文章:

django - 当时区支持处于事件状态时,DateTimeField 收到一个简单的日期时间

django - Rest-auth 中的自定义用户模型 : RelatedObjectDoesNotExist

python urllib2.HTTPError : HTTP Error 403: Forbidden

python - Matplotlib:检查是否未定义显示

python - Tensorflow SxN矩阵乘以SxD矩阵输出SxNxD数组

python - 我尝试安装 "pip install mysqlclient"但每次都失败。尝试了所有其他方法,但也没有成功。我应该怎么办?

django - 将客户端 IP 信息添加到 Django 记录器中

python - 在开发中提供静态文件

python - 如何在SimpleCV或opencv中计算边界内的标记区域

Python:避免分数简化