【问题标题】:Getting corrupt zips using Python3 ZipStream in Django在 Django 中使用 Python3 ZipStream 获取损坏的 zip
【发布时间】:2022-01-11 12:14:36
【问题描述】:

我正在使用来自here 的 zipstream,并且有一个 Django 视图,该视图返回一个包含所有文件附件的 zip 文件,这些附件都托管在 Amazon S3 上。但是当我下载它们时,所有的 zip 文件都显示为损坏,也就是说,我无法打开它们。

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

【问题讨论】:

    标签: python-3.x django zipstream


    【解决方案1】:

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

    #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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多