📜  在Python中使用 UUID 生成随机 id

📅  最后修改于: 2022-05-13 01:55:50.750000             🧑  作者: Mango

在Python中使用 UUID 生成随机 id

我们在Python中生成随机 ID 中讨论了在Python中生成唯一 ID 的方法,而无需使用任何Python内置库

在本文中,我们将使用内置函数来生成它们。

UUID,Universal Unique Identifier,是一个Python库,有助于生成 128 位的随机对象作为 id。它提供了唯一性,因为它根据时间、计算机硬件(MAC 等)生成 ID。

UUID 的优点:

  • 可用作生成唯一随机 id 的通用实用程序。
  • 可用于加密和散列应用程序。
  • 可用于生成随机文档、地址等。

方法 1:使用 uuid1()

uuid1() 在 UUID 库中定义,有助于使用MAC 地址和时间组件生成随机 id。

# Python3 code to generate the
# random id using uuid1()
  
import uuid
  
# Printing random id using uuid1()
print ("The random id using uuid1() is : ",end="")
print (uuid.uuid1())

输出 :

The random id using uuid1() is : 67460e74-02e3-11e8-b443-00163e990bdb

uuid1() 的表示

  • bytes:以 16 字节字符串的形式返回 id。
  • int :以 128 位整数形式返回 id。
  • hex:将随机 id 作为 32 个字符的十六进制字符串返回。

uuid1() 的组成部分

  • version : UUID 的版本号。
  • variant :确定 UUID 内部布局的变体。

uuid1() 的字段

  • time_low : id 的前 32 位。
  • time_mid : id 的下 16 位。
  • time_hi_version : id 的下 16 位。
  • clock_seq_hi_variant : id 的下 8 位。
  • clock_seq_low : id 的下 8 位。
  • node : id 的最后 48 位。
  • time : id 的时间分量字段。
  • clock_seq : 14 位序列号。
# Python3 code to demonstrate
# components, representations 
# and variants of uuid1()
  
import uuid
  
id = uuid.uuid1()
  
# Representations of uuid1()
print ("The Representations of uuid1() are : ")
print ("byte Representation : ",end="")
print (repr(id.bytes))
  
print ("int Representation : ",end="")
print (id.int)
  
print ("hex Representation : ",end="")
print (id.hex)
  
print("\n")
  
# Components of uuid1()
print ("The Components of uuid1() are : ")
print ("Version  : ",end="")
print (id.version)
  
print ("Variant : ",end="")
print (id.variant)
  
print("\n")
  
# Fields of uuid1()
print ("The Fields of uuid1() are : ")
print ("Fields  : ",end="")
print (id.fields)
  
print("\n")
  
# Time Component of uuid1()
print ("The time Component of uuid1() is : ")
print ("Time component  : ",end="")
print (id.node)

输出 :

The Representations of uuid1() are : 
byte Representation : b'k\x10\xa1n\x02\xe7\x11\xe8\xaeY\x00\x16>\x99\x0b\xdb'
int Representation : 142313746482664936587190810281013480411
hex Representation : 6b10a16e02e711e8ae5900163e990bdb


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


The Fields of uuid1() are : 
Fields  : (1796252014, 743, 4584, 174, 89, 95539497947)


The time Component of uuid1() is : 
Time component  : 95539497947

缺点:
这种方式包括使用计算机的 MAC 地址,因此会损害隐私,即使它提供了唯一性。

方法 2:使用 uuid4()
此函数保证随机编号。并且不妥协隐私。

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

输出 :

The id generated using uuid4() : fbd204a7-318e-4dd3-86e0-e6d524fc3f98