1

I have a bytea object in a database which is a zip file, I can retrieve it and read it as a zip file, but I also want to save it to disk.

I can't work out how to write zf_model to disk. I've also tried zf.write(io.BytesIO(model.model_file)), i.e. not converting to zip first, but that doesn't work either.

This is what I've tried:

from zipfile import ZipFile
from io import BytesIO
        
#Retrieve the zip file from database (zip file is in a field called model_file for object: Model)
model = Model().query.filter_by(param = "test").first()
#convert the retrieved object to a zip file
zf_model = ZipFile(BytesIO(model.model_file), "w")
    
tempfile = "/tmp/test.zip"

with zipfile.ZipFile(tempfile, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    zf.write(zf_model)

Gives error:

TypeError: a bytes-like object is required, not 'ZipFile'

Trying to write the bytea object directly

with open(tempfile, 'w+') as f:
    f.write(model.model_file)      

gives error:

TypeError: write() argument must be str, not bytes
yahop19531
  • 193
  • 1
  • 11

1 Answers1

1

If you retrieve already compressed file from database you may write it to disk without using ZipFile at all.

#Retrieve the zip file from database (zip file is in a field called model_file for object: Model)
model = Model().query.filter_by(param = "test").first()

tempfile = "/tmp/test.zip"

with open(tempfile, 'wb') as f:
    f.write(model.model_file)

Anyway, if your model store plain bytes data (not zipped one), you may do the following

from zipfile import ZipFile

#Retrieve the zip file from database 
model = Model().query.filter_by(param = "test").first()

tempfile = "/tmp/test.zip"

with ZipFile(tempfile, 'w') as f:
    f.writestr('name_of_file_in_zip_archive.txt', model.model_file)
Mullo
  • 106
  • 5
  • Are you still using `zf_model = ZipFile(BytesIO(model.model_file), "w")` ? Tried that and got: `TypeError: write() argument must be str, not bytes` – yahop19531 Jul 29 '20 at 10:18
  • Nope, i missed variable in write. Now i edited my answer. You retrieve ZIP file from database, so you need not to compress it again. – Mullo Jul 29 '20 at 10:22
  • Sorry, `model.model_file` is `bytea` so I was converting to zip using `zf_model = ZipFile(BytesIO(model.model_file), "w")`. Trying to write the `bytea` object directly gives me `TypeError: write() argument must be str, not bytes` – yahop19531 Jul 29 '20 at 10:33
  • 1
    changing to `with open(tempfile, 'wb') as f:` works – yahop19531 Jul 29 '20 at 11:00