python - Django:使用 django-storage 从 S3 创建 zipfile

我使用 django-storages并将与用户相关的内容存储在 S3 上的文件夹中。现在,我希望用户能够一次下载所有文件,最好是 zip 文件。之前所有与此相关的帖子都已过时或对我不起作用。

目前为止最接近工作的代码:

from io import BytesIO
import zipfile
from django.conf import settings
from ..models import Something
from django.core.files.storage import default_storage

class DownloadIncomeTaxFiles(View):

    def get(self, request, id):
        itr = Something.objects.get(id=id)
        files = itr.attachments
        zfname = 'somezip.zip'
        b =  BytesIO()
        with zipfile.ZipFile(b, 'w') as zf:
            for current_file in files:
                try:
                    fh = default_storage.open(current_file.file.name, "r")
                    zf.writestr(fh.name, bytes(fh.read()))
                except Exception as e:
                    print(e)
            response = HttpResponse(zf, content_type="application/x-zip-compressed")
            response['Content-Disposition'] = 'attachment; filename={}'.format(zfname)
            return response

这会创建一个看起来像 zip 文件的文件,但它唯一的内容是“

我得到了许多不同的结果,主要是错误,例如 zipfile 在提供 FieldFile 时需要字符串或字节内容。在这一点上,我完全卡住了。

最佳答案

问题是我需要通过添加恢复到文件的开头

zf.seek(0)

就在 HttpResponse 中返回文件之前。

https://stackoverflow.com/questions/63566438/

相关文章:

python - 通过 Python 的 gRPC API 服务器无法工作

Python - 在 asyncio 中取消任务?

c# - 如何从 .NET Core 3.1 中的 DI 获取 SignalR IHubContex

python-3.x - TypeError : on heapq. heapop on pytho

python - 如何启用对 Dash DataTable 上特定行的编辑

php - 带有 "sometimes"规则的 Laravel Validator 自定义消息

python - 对包含 str 和元组的 Pandas MultiIndex 进行排序

java - 无法在 Linux 上的 Intellij 中指定 SDK

git - 以编程方式为新的 Azure 存储库设置默认分支名称

amazon-web-services - AWS API 网关上的剥离 header