类型错误:无法将 psycopg2.extensions.Binary 转义为二进制 [英] TypeError: can't escape psycopg2.extensions.Binary to binary

查看:87
本文介绍了类型错误:无法将 psycopg2.extensions.Binary 转义为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过 sqlalchemy 将二进制文件存储到 postgresql 中,并且文件是从客户端上传的.关于错误消息的一点谷歌让我看到这个源文件:包装的对象不是字节或缓冲区,这是一个错误"

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 escaping
    mytable=mytable(
    ...,
    document1 = binaries[0]
    ...
    )
    #Model
    class mytable(mydb.Model):
      document1 = mydb.Column(mydb.LargeBinary())

推荐答案

不需要将文件中的字节转换为 psycopg2.Binary.它会在 SQLAlchemy 将语句和值发送到数据库时自动发生(使用 DBAPI 连接器,在本例中为 psycopg2).

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

类似的东西

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

适用于 Python2 和 Python3,SQLAlchemy 1.3.x,从引擎生成此输出:

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>}

这篇关于类型错误:无法将 psycopg2.extensions.Binary 转义为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆