实现说明
record_key、record_id、other 定义在模块顶层,中间不经过函数作用域。
使用要点
- 演示输出是带标签的(
invoices ns:、recompute matches?、namespaces differ?),每个操作都会留下自己的一行标注。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 状态都挂在模块顶层:record_key、record_id、other。
代码示例
import uuid
# uuid5 = 命名空间 UUID + 名称 做 SHA-1:同样输入在任何机器都得到同一 ID
ORDERS = uuid.uuid5(uuid.NAMESPACE_DNS, "orders.example.internal")
INVOICES = uuid.uuid5(uuid.NAMESPACE_DNS, "invoices.example.internal")
print("orders ns :", ORDERS)
print("invoices ns:", INVOICES)
# 从自然键派生记录 ID:重跑、重试、多副本写入都落到同一行,天然幂等
record_key = "customer-42#2026-11"
record_id = uuid.uuid5(ORDERS, record_key)
print("record id :", record_id)
print("recompute matches?", uuid.uuid5(ORDERS, record_key) == record_id)
# 不同命名空间隔离同名键;uuid.UUID 与字符串形式无损往返
other = uuid.uuid5(INVOICES, record_key)
print("namespaces differ?", record_id != other)
print("roundtrip stable?", uuid.UUID(str(record_id)) == record_id)