0

我有一个这样的Django模型:


class Todo(models.Model):
    big_file = models.FileField(blank=True)
    status = models.PositiveSmallIntegerField(default=0)
    progress = models.IntegerField(default=0)

我想做两个操作:

  • 首先制作一个空的zipfile big_file(不太重要)
  • 然后逐步将文件添加到我的 zipfile 中(并迭代保存)

整个过程如下所示:

from django.core.files.base import File
import io, zipfile

def generate_data(todo):
    io_bytes = io.BytesIO(b'')
    # 1. save an empty Zip archive:
    with zipfile.ZipFile(io_bytes, 'w') as zip_fd:
        todo.generated_data.save('heavy_file.zip', File(zip_fd))

    # 2. Progressively fill the Zip archive:
    with zipfile.ZipFile(io_bytes, 'w') zip_fd:
        for filename, data_bytes in long_iteration(todo):
            with zip_fd.open(filename, 'w') as in_zip:
                in_zip.write(data_bytes)
            if condition(something):
                todo.generated_data.save()  # that does not work
                todo.status = 1
                todo.progress = 123
                todo.save()
    todo.status = 2
    todo.save()

但我无法找出正确的文件描述符/类文件对象/文件路径/django-File对象组合......而且似乎在django中我总是必须 save(filename, content). 但是我的内容可能是千兆字节,所以将它全部存储到“内容”变量中听起来不合理?

4

1 回答 1

0

好的,我为自己找到了以下解决方案;首先创建一个空文件,然后使用<my_file_field>.path属性:


def generate_data(todo):
    # 1. save an empty Zip archive:
    todo.big_file.save('filename.zip', ContentFile(''))
    with zipfile.ZipFile(todo.big_file.path, 'w') as zip_fd:
        pass

    # 2. Progressively fill the Zip archive:
    with zipfile.ZipFile(todo.big_file.path, 'w') zip_fd:
        ... # do the stuff 

于 2022-02-08T15:21:58.057 回答