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)
5
  • Why are you opening the file for write? Commented Jul 28, 2020 at 16:47
  • attempting to convert to bytea - is there a way of doing that without opening it? Commented Jul 28, 2020 at 16:48
  • Does the file, test.zip already exist? Commented Jul 28, 2020 at 16:49
  • yes, I just need to get it from the disk to a database Commented Jul 28, 2020 at 16:50
  • What is the actual error that you are observing? If you add an error message or stacktrace, there are more chances to correctly diagnose the problem. Commented Jul 28, 2020 at 17:41

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

OP asked specifically about python implementation, not php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.