← 中文资源

简体中文版本

uuid5 从命名空间派生稳定 ID

用 uuid5 从命名空间 UUID 加自然键派生确定性 ID:同样的输入在任何机器上都得到同一个 ID,重跑与 upsert 天然幂等,不同命名空间还能隔离同名键。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

orders ns  : 78533f7f-fea6-557f-a304-ff86b0151025
invoices ns: 9780afd8-01e2-54a8-b3be-12dfa45eedd2
record id  : 308e6ee3-d2cf-5e66-b87b-969b06b0e905
recompute matches? True
namespaces differ? True
roundtrip stable? True

实现说明

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)