使用 UUID 库生成唯一 ID

UUID(Universally Unique IDentifier) 是128位的全局唯一标识符,通常由32字节的字符串表示。它可以保证时间和空间的唯一性,也称为 GUID(Globally Unique IDentifier)。

它通过MAC地址、时间戳、命名空间、随机数、伪随机数来保证生成ID的唯一性。

分类

在 python 中 UUID 主要有四种实现:

  • uuid1() ——基于时间戳

由 MAC 地址、当前时间戳、随机数生成。可以保证全球范围内的唯一性,但 MAC 的使用同时带来安全性问题,局域网中可以使用 IP 来代替 MAC。

  • uuid3() ——基于名字的 MD5 散列值

通过计算名字和命名空间的 MD5 散列值得到,保证了同一命名空间中不同名字的唯一性,和不同命名空间的唯一性,但同一命名空间的同一名字生成相同的 uuid。

  • uuid4() ——基于随机数

由伪随机数得到,有一定的重复概率,该概率可以计算出来。

  • uuid5() ——基于名字的 SHA-1 散列值

算法与 uuid3 相同,不同的是使用 Secure Hash Algorithm 1 算法

使用方面

  • uuid4 存在概率性重复,最好不用
  • 若在 Global 的分布式计算环境下,最好用 uuid1
  • 若有名字的唯一性要求,最好用 uuid3 或 uuid5

编码方法

>>> 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')

实际参考

week, month, day, time_now, year = time.ctime().split()
check_time = year+ month + day + week + time_now
check_time + str(uuid.uuid4())
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容