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 is not bytes or a buffer, this is an error"
binaries = []for f in request.files.values():if f and allowed_file(f.filename):fn = secure_filename(f.filename)file_path = os.path.join(basedir, fn)f.save(file_path)#data = f.read()data = open(fn, 'rb').read()binaries.append(psycopg2.Binary(data))f.close()#does the escapingmytable=mytable(...,document1 = binaries[0]...)#Modelclass mytable(mydb.Model):document1 = mydb.Column(mydb.LargeBinary())
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
with open(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>}