20.15. uuid —符合 RFC 4122 的 UUID 对象

2.5 版的新Function。

此模块提供不可变的UUID对象(UUID类)和函数uuid1()uuid3()uuid4()uuid5(),以生成 RFC 4122中指定的版本 1、3、4 和 5 UUID。

如果您只需要一个唯一的 ID,则应该致电uuid1()uuid4()。请注意,uuid1()可能会破坏隐私,因为它会创建一个包含计算机网络地址的 UUID。 uuid4()创建一个随机 UUID。

UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes='\x12\x34\x56\x78'*4)
UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
              '\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)

必须给出* hex bytes bytes_le fields int *之一。 * version 参数是可选的;如果给出,则所得的 UUID 将根据 RFC 4122 设置其变体和版本号,覆盖给定 hex bytes bytes_le fields int *中的位。

UUID个实例具有以下只读属性:

Field Meaning
time_low UUID 的前 32 位
time_mid UUID 的后 16 位
time_hi_version UUID 的后 16 位
clock_seq_hi_variant UUID 的后 8 位
clock_seq_low UUID 的后 8 位
node UUID 的最后 48 位
time 60 位时间戳
clock_seq 14 位序号

uuid模块定义以下Function:

uuid模块定义以下用于uuid3()uuid5()的名称空间标识符。

uuid模块为variant属性的可能值定义以下常量:

See also

  • RFC 4122-通用唯一标识符(UUID)URN 命名空间

  • 该规范定义了 UUID 的统一资源名称名称空间,UUID 的内部格式以及生成 UUID 的方法。

20.15.1. Example

以下是uuid模块的典型用法的一些示例:

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
首页