ZipFile 到文件到 FileField Django Python

ZipFile to File to FileField Django Python

我正在从一个 API 打电话给我一个包含两个文件的 zip 文件。 我设法提取了我需要的文件(因为它是 PDF)

现在我无法找到一个解决方案来将它保存在我的文件字段中而不在我的电脑中创建文件。

        with ZipFile(io.BytesIO(response3.content)) as z: # response3 is my response to the API
            for target_file in z.namelist():
                if target_file.endswith('pdf'):
                    z.extract(member=target_file) # that's how i can have acces to my file and know it is a valid PDF

                    # here begin the trick
                    with io.BytesIO() as buf:
                        z.open(target_file).write(buf)
                        buf.seek(0)
                    f = File.open(buf) # File is an import of django.core.files
                    rbe, created = RBE.objects.update_or_create(file=f)

使用此代码,我在写入 z.open(...) 时出错。如下所示:

    z.open(target_file).write(buf)
io.UnsupportedOperation: write

谢谢:)

因此,经过 2 次偏头痛和 1 次愤怒戒烟的艰苦努力,我终于成功了。

希望对某人有所帮助

        with ZipFile(io.BytesIO(response3.content), 'r') as z:
            for target_file in z.namelist():
                if target_file.endswith('pdf'):
                    with z.open(target_file) as myfile:
                        with io.BytesIO() as buf:
                            buf.write(myfile.read())
                            buf.seek(0)
                            file = File(buf, target_file) # still the File from django
                            rbe = RBE.objects.create(file=file, establishment=establishment)