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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29268978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:50:10  来源:igfitidea点击:

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

pythonpostgresqlpsycopg2bytea

提问by Clicquot the Dog

I have a small script where I'm generating SHA1 hashes, taking the binary representation through hashlib's hexdigest, and storing them in a Postgres DB with a bytea column. I have a query that looks like this in Postgres (abbreviated):

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

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

When executing a query, I have some code that looks like this:

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

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

Now, in that print statement, it will either print out unintelligible characters, or if I change it to:

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

print str(psycopg2.Binary(bhash))

I get something like:

我得到类似的东西:

'4p307K73o3'::bytea

What is the correct way to convert it back to the original string? The original representations are something like "30d22d5d64efe4c5333e", and I'd like to get it back to that original string for comparison purposes. I'm not sure if I'm missing something obvious,

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

回答by Lie Ryan

Since you asked Postgres to decode your hex string and stores it as binary, you should ask postgres to encode it back to hex on output.

由于您要求 Postgres 解码您的十六进制字符串并将其存储为二进制文件,因此您应该要求 postgres 在输出时将其编码回十六进制。

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

Alternatively, you can do the encoding in python. Try binascii.hexlify(data).

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