简体   繁体   中英

Converting a zip file to bytea to store in postgres - python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM