I would like to store zip files in a postgres database using python.
It seems like this should be easy, but I can't work it out.
This is what I've tried - my issue is how to convert the zipfile to a bytea
object.
from zipfile import ZipFile
from io import BytesIO, StringIO
filename = "test.zip"
with ZipFile(filename, 'w') as zip_archive:
binary_stream = BytesIO(zip_archive)
def store_blob(filename, blob):
with db.engine.connect() as connection:
res = connection.execute('''INSERT INTO test (filename, model_file) VALUES (%s, %s)''', (filename, blob ))
store_blob(filename, binary_stream)
If the file already exists, then your code should look like this:
def store_blob(filename, blob):
with db.engine.connect() as connection:
res = connection.execute(
'''INSERT INTO test (filename, model_file) VALUES (%s,%s)''',
(filename, blob ))
filename = "test.zip"
with open(filename, 'rb') as zip_archive:
store_blob(filename, zip_archive.read())
Your code does not need to know about the format of the file. All you want to do is to open it for read
with the binary
flag to prevent decoding, and pass its read()
(which produces a b''
) as a parameter to the execute()