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

Clicquot the Dog picture Clicquot the Dog · Mar 26, 2015 · Viewed 14.9k times · Source

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,

Answer

Lie Ryan picture Lie Ryan · Mar 26, 2015

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