将 bytea 从 Postgres 转换回 python 中的字符串的正确方法

Proper way to convert bytea from Postgres back to a string in python

我有一个小脚本,我在其中生成 SHA1 哈希,通过 hashlib 的 hexdigest 获取二进制表示,并将它们存储在带有 bytea 列的 Postgres 数据库中。我在 Postgres 中有一个看起来像这样的查询(缩写):

SELECT * FROM some_table WHERE some_hash in decode(another_hash, 'hex')

执行查询时,我有一些代码如下所示:

cur.execute(query)
for hash_rep in cur:
    print bhash

现在,在那个 print 语句中,它会打印出无法理解的字符,或者如果我将其更改为:

print str(psycopg2.Binary(bhash))

我得到类似的东西:

'4p307K73o3'::bytea

将其转换回原始字符串的正确方法是什么?原始表示类似于“30d22d5d64efe4c5333e”,我想将其恢复为原始字符串以进行比较。我不确定我是否遗漏了一些明显的东西,

既然你要求 Postgres 解码你的十六进制字符串并将其存储为二进制,你应该要求 postgres 在输出时将它编码回十六进制。

SELECT encode(some_hash, 'hex'), * FROM some_table WHERE some_hash in decode(another_hash, 'hex')

或者,您可以在 python 中进行编码。试试 binascii.hexlify(data).