0

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)
yahop19531
  • 193
  • 1
  • 11

2 Answers2

1

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()

Mike Organek
  • 11,647
  • 3
  • 11
  • 26
0

I believe there's an accepted answer here already Storing Zip file in Postgres

You can use the bin2hex() function as demonstrated in the above answer.

Info on postgres bytea datatypes: https://www.postgresql.org/docs/current/datatype-binary.html#AEN5318

jaimish11
  • 536
  • 4
  • 15