在我的 Python 应用程序中,我有一个接受 128 位值 (_id: uuid.UUID) 的函数。我需要使用
pg_advisory_xact_lock
将此值存储到 postgres 数据库中作为咨询锁,它需要 bigInt
类型,它是一个 64 位整数。解决这个问题的最佳方法是什么?我应该使用某种哈希表吗?
我不知道您尝试过什么,但您可以使用哈希函数来减小 UUID 的大小,同时保持唯一性。您可以遵循以下一般方法:
import hashlib
import uuid
def uuid_to_int(uuid_val):
# Convert the UUID to bytes
uuid_bytes = uuid_val.bytes
# Calculate a hash of the UUID bytes (using MD5 in this example)
md5_hash = hashlib.md5(uuid_bytes)
# Take the first 8 bytes of the MD5 hash and convert them to an integer
result = int.from_bytes(md5_hash.digest()[:8], byteorder='big')
return result