Computer >> Máy Tính >  >> Lập trình >> Python

Tạo id ngẫu nhiên bằng UUID trong Python

UUID có dạng đầy đủ là Số nhận dạng duy nhất phổ quát, nó là một thư viện python hỗ trợ id 128 bit để tạo các đối tượng ngẫu nhiên.

Ưu điểm của UUID

  • Như đã thảo luận, chúng ta có thể sử dụng nó để tạo id ngẫu nhiên duy nhất cho các đối tượng ngẫu nhiên.
  • Đối với các ứng dụng mật mã và băm, id này có thể được sử dụng.
  • Để tạo các tài liệu ngẫu nhiên và cả địa chỉ, v.v., bạn có thể sử dụng id này.

Phương pháp 1

Sử dụng uuid1 ()

Mã mẫu

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

Đầu ra

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

Trình bày của uuid1 ()

byte - Nó trả về id ở định dạng chuỗi 16 byte.

int - Nó trả về id ở định dạng số nguyên 128 bit.

hex - Dưới dạng chuỗi thập lục phân gồm 32 ký tự, nó trả về id ngẫu nhiên.

Các thành phần của uuid1 ()

phiên bản - số phiên bản của UUID.

biến thể - Nó xác định bố cục bên trong của UUID.

Các trường uuid1 ()

time_low −Cho biết 32 bit đầu tiên của id.

time_mid −Cho biết 16 bit tiếp theo của id.

time_hi_version - Cho biết 16 bit tiếp theo của id.

clock_seq_hi_variant - Cho biết 8 bit tiếp theo của id.

clock_seq_low - Cho biết 8 bit tiếp theo của id.

nút - Cho biết 48 bit cuối cùng của id.

thời gian - Chỉ ra trường thành phần thời gian của id.

clock_seq - Cho biết số thứ tự 14 bit.

Mã mẫu

import uuid
id = uuid.uuid1()
# Representations of 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 of uuid1()
print ("Different Components of uuid1() are : ")
print ("UUID Version : ",end="")
print (id.version)
print ("UUID Variant : ",end="")
print (id.variant)
print("\n")
# Fields of 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)

Đầu ra

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

Phương pháp 2

Sử dụng uuid4 ()

Mã mẫu

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

Đầu ra

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