Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 934
Clicquot the Dog Avatar asked Mar 26 '15 00:03

Clicquot the Dog


1 Answers

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

like image 173
Lie Ryan Avatar answered Oct 23 '22 14:10

Lie Ryan