[英]Getting corrupt zips using Python ZipStream in Django
I am a little new to Django so please bear with me. 我是Django的新手,请耐心等待。
I'm using zipstream from here and have a Django view that returns a zip file of all file attachments which are all hosted on Amazon S3. 我从这里使用zipstream,并具有Django视图,该视图返回所有文件附件的zip文件,这些文件附件都托管在Amazon S3上。 But the zip files are all coming up as corrupt when I download them, that is, I can't open them.
但是,当我下载zip文件时,它们都已损坏,也就是说,我无法打开它们。 I have tried verifying the files with
unzip -t
but the errors are not very helpful. 我尝试用
unzip -t
验证文件,但错误不是很有帮助。
file_paths = [fa.file.url for fa in file_attachments.all()]
zf = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED)
zip_subdir = "Attachments-%s" % (request_id)
for file_path in file_paths:
file_dir, file_name = os.path.split(file_path)
zf.writestr(file_name, urllib.urlopen(file_path).read())
zip_filename = "%s.zip" % (zip_subdir)
response = StreamingHttpResponse(zf, mimetype='application/zip')
response['Content-Disposition'] = \
'attachment; filename={}'.format(zip_filename)
return response
Any ideas? 有任何想法吗?
Solved it. 解决了。
s = StringIO.StringIO()
with zipstream.ZipFile(s, mode='w', compression=zipstream.ZIP_DEFLATED) as zf:
#could fail on url open.
for file_path in file_paths:
file_dir, file_name = os.path.split(file_path)
try:
file_contents = urllib.urlopen(file_path).read()
zf.writestr(file_name, file_contents)
except IOError: #connection cannot be made
logging.error()
response = StreamingHttpResponse(s.getvalue(), mimetype='application/octet-stream')
response['Content-Disposition'] = \
'attachment; filename={}'.format("%s" % (request_id))
return response
You should close the ZipFile
when you're done writing to it. 完成对
ZipFile
写入后,应将其关闭。 Otherwise, to quote the documentation , "essential records will not be written" until you do. 否则,要引用该文档 ,除非您这样做,否则“将不会写入必要的记录”。
The cleanest way to do it is using the with
statement: 最简单的方法是使用
with
语句:
with zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED) as zf:
# ...write to zf...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.