我想将我的服务器上的许多文件打包并制作一个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/