我尝试通过 sqlalchemy 将二进制文件存储到 postgresql 中,并且文件是从客户端上传的。
对错误消息进行了一番谷歌,让我明白了这个源文件 https://github.com/psycopg/psycopg2/blob/master/psycopg/adapter_binary.c:“包装的对象不是字节或缓冲区,这是一个错误”
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 escaping
mytable=mytable(
...,
document1 = binaries[0]
...
)
#Model
class mytable(mydb.Model):
document1 = mydb.Column(mydb.LargeBinary())
将文件中的字节转换为psycopg2.Binary
是不必要的。当 SQLAlchemy 将语句和值发送到数据库时(使用 DBAPI 连接器,在本例中为 psycopg2),它将自动发生。
就像是
with open(fn, 'rb') as f:
bytes_ = f.read()
instance = MyModel(document1=bytes_)
session.add(instance)
session.commit()
适用于 Python2 和 Python3、SQLAlchemy 1.3.x,从引擎生成以下输出:
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>}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)