Django - 生成 Zip 文件并提供服务(在内存中)

Mil*_*ano 3 python django zip

我正在尝试提供zip包含Django对象图像的文件。

问题是,即使返回 Zip 文件,它也已损坏。

注意:由于我使用远程存储,因此我无法使用文件的绝对路径。

应在内存中生成 zip 的模型方法

def generate_images_zip(self) -> bytes:
    content = BytesIO()
    zipObj = ZipFile(content, 'w')
    for image_fieldname in self.images_fieldnames():
        image = getattr(self, image_fieldname)
        if image:
            zipObj.writestr(image.name, image.read())
    return content.getvalue()
Run Code Online (Sandbox Code Playgroud)

视图集动作

@action(methods=['get'], detail=True, url_path='download-images')
def download_images(self, request, pk=None) -> HttpResponse:
    product = self.get_object()
    zipfile = product.generate_images_zip()
    response = HttpResponse(zipfile, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=images.zip'
    return response
Run Code Online (Sandbox Code Playgroud)

当我尝试打开下载的 Zip 文件时,它说它已损坏。

你知道如何让它发挥作用吗?

Abd*_*kat 5

您犯了一个非常菜鸟的错误,即打开文件后不调用close/关闭文件(ZipFile此处),最好使用ZipFile作为上下文管理器:

def generate_images_zip(self) -> bytes:
    content = BytesIO()
    with ZipFile(content, 'w') as zipObj:
        for image_fieldname in self.images_fieldnames():
            image = getattr(self, image_fieldname)
            if image:
                zipObj.writestr(image.name, image.read())
    return content.getvalue()
Run Code Online (Sandbox Code Playgroud)