Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

สร้าง Hash ID ด้วย uuid3() และ uuid5() ใน Python

UUID (Universally Unique Identifier) เป็นตัวระบุ 128-bit (32 hex digits) มาตรฐาน RFC 4122 Python มี uuid module สร้าง UUID ได้หลายรุ่น

uuid3() และ uuid5() - Namespace-based UUID

  • uuid3(namespace, name): ใช้ MD5 Hash
  • uuid5(namespace, name): ใช้ SHA-1 Hash (แนะนำ มากกว่า)
  • Deterministic: Input เดียวกัน → UUID เดียวกันเสมอ

Namespace มาตรฐาน

  • uuid.NAMESPACE_DNS - Domain Name
  • uuid.NAMESPACE_URL - URL
  • uuid.NAMESPACE_OID - ISO OID
  • uuid.NAMESPACE_X500 - X.500 DN

ตัวอย่างโค้ด Python

import uuid

name_dns = "www.tutorialspoint.com"
name_url = "https://www.tutorialspoint.com"

print("uuid3 (MD5) + DNS:", uuid.uuid3(uuid.NAMESPACE_DNS, name_dns))
print("uuid3 (MD5) + URL:", uuid.uuid3(uuid.NAMESPACE_URL, name_url))
print("uuid5 (SHA-1) + DNS:", uuid.uuid5(uuid.NAMESPACE_DNS, name_dns))
print("uuid5 (SHA-1) + URL:", uuid.uuid5(uuid.NAMESPACE_URL, name_url))

ผลลัพธ์ (ตัวอย่าง)

uuid3 (MD5) + DNS: e5051d13-d1a5-381a-bc21-5017b275a7f2
uuid3 (MD5) + URL: de365612-734a-38e3-abc4-6e3ffc7d61db
uuid5 (SHA-1) + DNS: a064f94e-5ff6-51e4-88e2-e2163a79abce
uuid5 (SHA-1) + URL: b9761e0a-0ef3-5fd3-9ec4-86b6e073e61b

UUID Versions อื่นๆ

VersionMethodUse Case
uuid1()Time + MAC AddressUnique ตามเวลา/เครื่อง
uuid4()RandomGeneral Purpose (แนะนำมากที่สุด)
uuid3()MD5 HashLegacy/Compatibility
uuid5()SHA-1 HashDeterministic, Security-sensitive

แนะนำ: ใช้ uuid4() สำหรับ General Unique ID, ใช้ uuid5() เมื่อต้องการ Deterministic ID จาก Name