在Djang中使用Python ZipStream获取损坏的zip

2024-06-07 06:44:57 发布

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

我对Django有点陌生,所以请耐心等待。
我使用的是来自here的zipstream,它有一个Django视图,它返回所有文件附件的zip文件,这些附件都托管在amazons3上。但是当我下载这些zip文件时,它们都会被破坏,也就是说,我无法打开它们。我尝试过用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

有什么想法吗?在

解决了。在

^{pr2}$

Tags: 文件pathdjangoinfor附件responsezip
1条回答
网友
1楼 · 发布于 2024-06-07 06:44:57

完成对ZipFile的写入后,应将其关闭。否则,引用documentation,“基本记录将不会被写入”直到您这样做。在

最干净的方法是使用with语句:

with zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED) as zf:
    # ...write to zf...

相关问题 更多 >