简体   繁体   中英

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

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

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:

'\214p\203\030\017K\247\373o\253'::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,

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM