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(...).write, как показано ниже:

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

Спасибо :)

Итак, после напряженной работы, 2 мигреней и 1 ragequit я наконец-то справился с этим.

Надеюсь, это может кому-то помочь

        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)

Вернуться на верх