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

สร้าง Random IDs ด้วย UUID ใน Python

UUID ย่อมาจาก Universal Unique Identifier เป็นไลบรารี Python ที่รองรับ 128 bits IDs สำหรับสร้าง random objects

ข้อดีของ UUID

  • ใช้สร้าง unique random id สำหรับ random objects
  • สำหรับ cryptography และ hashing applications สามารถใช้ id นี้ได้
  • สำหรับสร้าง random documents และ addresses ฯลฯ สามารถใช้ id นี้ได้

วิธีที่ 1

ใช้ uuid1()

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

import uuid
print("Random id using uuid1() is : ", end="")
print(uuid.uuid1())

ผลลัพธ์

Random id using uuid1() is : 4adeede2-e5d8-11e8-bd27-185e0fd4f8b3

Representations ของ uuid1()

bytes − คืนค่า id ในรูปแบบ 16 byte string

int − คืนค่า id ในรูปแบบ 128-bit integer

hex − เป็น 32 character hexadecimal string คืนค่า random id

Components ของ uuid1()

version − version number ของ UUID

variant − กำหนด internal layout ของ UUID

Fields ของ uuid1()

time_low − บ่งชี้ 32 bits แรกของ id

time_mid − บ่งชี้ 16 bits ถัดไปของ id

time_hi_version − บ่งชี้ 16 bits ถัดไปของ id

clock_seq_hi_variant − บ่งชี้ 8 bits ถัดไปของ id

clock_seq_low − บ่งชี้ 8 bits ถัดไปของ id

node − บ่งชี้ 48 bits สุดท้ายของ id

time − บ่งชี้ time component field ของ id

clock_seq − บ่งชี้ 14 bit sequence number

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

import uuid
id = uuid.uuid1()

# Representations ของ uuid1()
print("Different Representations of uuid1() are : ")
print("Representation in byte : ", end="")
print(repr(id.bytes))
print("Representation in int : ", end="")
print(id.int)
print("Representation in hex : ", end="")
print(id.hex)
print("\n")

# Components ของ uuid1()
print("Different Components of uuid1() are : ")
print("UUID Version : ", end="")
print(id.version)
print("UUID Variant : ", end="")
print(id.variant)
print("\n")

# Fields ของ uuid1()
print("Fields of uuid1() are : ")
print("UUID Fields : ", end="")
print(id.fields)
print("\n")

# uuid1() Time Component
print("uuid1() time Component is : ")
print("Time component : ", end="")
print(id.node)

ผลลัพธ์

Different Representations of uuid1() are :
Representation in byte : b'\x1a\xd2\xa7F\xe5\xe4\x11\xe8\xbd\x9c\x18^\x0f\xd4\xf8\xb3'
Representation in int : 35653703010223099234452630771665795251
Representation in hex : 1ad2a746e5e411e8bd9c185e0fd4f8b3

Different Components of uuid1() are :
UUID Version : 1
UUID Variant : specified in RFC 4122

Fields of uuid1() are :
UUID Fields : (450012998, 58852, 4584, 189, 156, 26792271607987)

uuid1() time Component is :
Time component : 26792271607987

วิธีที่ 2

ใช้ uuid4()

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

import uuid
id = uuid.uuid4()
# Id generated using uuid4()
print("The id generated using uuid4() : ", end="")
print(id)

ผลลัพธ์

The id generated using uuid4() : 21764219-e3d9-4bd3-a768-0bbc6e376bc0