Django如何将数据写入一个巨大的压缩文件FileField



我有一个django模型,如下所示:


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

我想做两个操作:

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

整个过程如下所示:

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()

但我无法找到合适的文件描述符/类文件对象/Filepath/django文件对象组合。。。似乎在django中,我总是要save(filename, content)。但我的内容可能是千兆字节,所以把它全部存储到";内容";变量

好的,我自己找到了以下解决方案;首先创建一个空文件,然后使用<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 

相关内容

最新更新