python 使用UUID库生成唯一ID

 
首先导包: import uuid
 
uuid1():
# make a UUID based on the host ID and current time    
#  基于MAC地址,时间戳,随机数来生成唯一的uuid,可以保证全球范围内的唯一性
>>> uuid.uuid1() # doctest: +SKIP
结果:UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
 
uuid3():
# make a UUID using an MD5 hash of a namespace UUID and a name
#  通过计算一个命名空间和名字的md5散列值来给出一个uuid,所以可以保证命名空间中的不同名字具有不同的uuid,但是相同的名字就是相同的uuid了
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
结果:UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
 
uuid4():
# make a random UUID
#  通过伪随机数得到uuid,是有一定概率重复的
>>> uuid.uuid4() # doctest: +SKIP
结果:UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
 
uuid5():
# make a UUID using a SHA-1 hash of a namespace UUID and a name
#  和uuid3基本相同,只不过采用的散列算法是sha1
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
结果:UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
 
相关函数:
# convert a UUID to a string of hex digits in standard form
# 将uuid对象转换成字符串
>>> str(x)
结果:'00010203-0405-0607-0809-0a0b0c0d0e0f'
 
# get the raw 16 bytes of the UUID
# 转化为字节序列
>>> x.bytes
结果:b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
posted @ 2018-03-23 14:59  kadima_zy  阅读(490)  评论(0编辑  收藏  举报