首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Django中使用Python3 ZipStream获取腐败的zip

在Django中使用Python3 ZipStream获取腐败的zip
EN

Stack Overflow用户
提问于 2022-01-11 12:14:36
回答 1查看 160关注 0票数 0

我使用来自这里的zip流,并有一个Django视图,该视图返回所有文件附件的压缩文件,这些附件都托管在S3上。但是当我下载的时候,压缩文件都被破坏了,也就是说,我不能打开它们。

代码语言:javascript
复制
import io
import zipstream
s = io.BytesIO()
with zipstream.ZipFile(s,"w", compression=zipstream.ZIP_DEFLATED) as zf:
    for file_path in file_paths:
        file_dir, file_name = os.path.split(file_path)

        zf.writestr(file_name, urllib.urlopen(file_path).read())

response = StreamingHttpResponse(s.getvalue(), content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename={}'.format('files.zip')
return response
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-17 16:07:05

而不是安装zipstream包,安装aiozipstream包。如果您已经安装了zipstream包,请先卸载它。pip卸载zipstream,然后执行pip安装aiozipstream

代码语言:javascript
复制
#Do the import in the same way
from zipstream import ZipStream
from django.http import StreamingHttpResponse

def s3_content_generator(key):
    #s3_bucket - your s3 bucket name
    infile_object = s3.get_object(Bucket=s3_bucket, Key= key)
    data = str(infile_object.get('Body', '').read())
    yield bytes(data, 'utf-8')


files = []
#filepath - list of s3 keys
for keyin filepath:
    files.append({'stream': s3_content_generator(key),'name': 'filename'})

#large chunksize fasten the download process
zf = ZipStream(files, chunksize=32768)
response = StreamingHttpResponse(zf.stream(), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename={}'.format('files.zip')
return response
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70666639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档