Reputation: 223
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
Upvotes: 2
Views: 2128
Reputation: 106
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)
Upvotes: 1