简体   繁体   中英

HEX() function in python sqlalchemy

I stored uuid4 without dashes using native UNHEX() as binary in MySQL and use native HEX() function to retrieve the uuid4.

Example:

UUID4: UNHEX("7D96F13AC8394EF5A60E8252B70FC179")
BINARY IN MySQL: }éŽ:·9NŠÙ ýRÈ ¾y
UUID4: HEX(UUID4Column)

This works fine to store and retrieve using its functions HEX() and UNHEX().

However, by using ORM sqlalchemy and declare UUID4Column as LargeBinary(16), the return value become b'}\x96\xf1:\xc89N\xf5\xa6\x0e\x82R\xb7\x0f\xc1y'

How can convert this bytes to 7D96F13AC8394EF5A60E8252B70FC179 in python code?

Without any imports:

You can use int.from_bytes and string formatting with 'X' to get the hexadecimal representation of the integer:

s = b'}\x96\xf1:\xc89N\xf5\xa6\x0e\x82R\xb7\x0f\xc1y'

nicer = f"{(int.from_bytes(s,byteorder='big')):X}"
print(nicer)

prints:

7D96F13AC8394EF5A60E8252B70FC179

You can use binascii.hexlify :

>>> import binascii
>>> bs = b'}\x96\xf1:\xc89N\xf5\xa6\x0e\x82R\xb7\x0f\xc1y'
>>> binascii.hexlify(bs)
b'7d96f13ac8394ef5a60e8252b70fc179'

>>> # for str result
>>> binascii.hexlify(bs).decode('ascii')
'7d96f13ac8394ef5a60e8252b70fc179'

This worked for me:

>>> print(b'}\x96\xf1:\xc89N\xf5\xa6\x0e\x82R\xb7\x0f\xc1y'.hex())
7d96f13ac8394ef5a60e8252b70fc179

Just pass your byte data in a variable or so and .hex() it for your answer. Like this:

byte_data = b'}\x96\xf1:\xc89N\xf5\xa6\x0e\x82R\xb7\x0f\xc1y'
print(byte_data.hex())

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