Skip to content Skip to sidebar Skip to footer

Typeerror: Can't Escape Psycopg2.extensions.binary To Binary

I try to store binary file into postgresql through sqlalchemy and file is uploaded from client. A bit google on the error message brings me to this source file:' wrapped object i

Solution 1:

Casting the bytes from the file to psycopg2.Binary is unnecessary. It will happen automatically when SQLAlchemy when sends the statement and values to the database (using the DBAPI connector, which would be psycopg2 in this case).

Something like

withopen(fn, 'rb') as f:
    bytes_ = f.read()
    instance = MyModel(document1=bytes_)
    session.add(instance)
    session.commit() 

works in both Python2 and Python3, SQLAlchemy 1.3.x, generating this output from the engine:

2020-09-06 10:39:27,775 INFO sqlalchemy.engine.base.Engine INSERT INTO mytable (document1) VALUES (%(document1)s) RETURNING mytable.id
2020-09-06 10:39:27,775 INFO sqlalchemy.engine.base.Engine {'document1': <psycopg2.extensions.Binary object at 0x7f8ea012ff60>}

Post a Comment for "Typeerror: Can't Escape Psycopg2.extensions.binary To Binary"