在Python中使用UUID生成随机id

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

null

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

UUID是一个python库,它可以帮助生成128位的随机对象作为ID。它提供了唯一性,因为它根据时间、计算机硬件(MAC等)生成ID。

UUID的优点:

  • 可作为通用工具生成唯一的随机id。
  • 可用于加密和哈希应用程序。
  • 用于生成随机文档、地址等。

方法1:使用uuid1()

uuid1()在UUID库中定义,有助于使用 MAC地址和时间组件 .

# 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()的表示

  • 字节: 以16字节字符串的形式返回id。
  • 智力: 以128位整数的形式返回id。
  • 十六进制: 以32个字符的十六进制字符串形式返回随机id。

uuid1()的组件

  • 版本: UUID的版本号。
  • 变体: 决定UUID内部布局的变量。

uuid1()的字段

  • 时间较短: id的前32位。
  • 时间(中) 接下来的16位id。
  • time_hi_版本: 接下来的16位id。
  • 时钟顺序高变量: 接下来的8位id。
  • 时钟顺序低: 接下来的8位id。
  • 节点: id的最后48位。
  • 时间: id的时间分量字段。
  • 时钟顺序: 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 ( "" )
# Components of uuid1()
print ( "The Components of uuid1() are : " )
print ( "Version  : " ,end = "")
print ( id .version)
print ( "Variant : " ,end = "")
print ( id .variant)
print ( "" )
# Fields of uuid1()
print ( "The Fields of uuid1() are : " )
print ( "Fields  : " ,end = "")
print ( id .fields)
print ( "" )
# 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'kx10xa1nx02xe7x11xe8xaeYx00x16>x99x0bxdb'
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
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享