首页 > 解决方案 > 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 7D96F13AC8394EF5A60E8252B70FC179in python code?

标签: pythonsqlalchemybinaryuuid

解决方案


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

推荐阅读