Python 在Django上创建临时zip文件,并在返回后将其删除
我想在我的服务器上打包许多文件,并制作一个zip文件,让人们从我的网站下载,一旦人们下载,该文件将被删除 我在stackoverflow上搜索,找到一些主题,但没有一个符合我的要求 这是我的密码:Python 在Django上创建临时zip文件,并在返回后将其删除,python,django,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.writ
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是一个类似文件的字符串缓冲区
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
FWIW,
cStringIO
比StringIO
快,但不能处理Unicode(非ASCII)字符--。在Python3中,您需要从io导入StringIO。