生成的最短唯一 ID

Rom*_*man 6 python uniqueidentifier python-3.x

所以我们可以生成一个唯一的idstr(uuid.uuid4()),它是 36 个字符长。

是否有另一种方法来生成一个字符较短的唯一 ID?

编辑:

  • 如果 ID 可用作主键,那就更好了
  • 粒度应优于1ms
  • 此代码可以分发,因此我们不能假设时间独立。

wim*_*wim 7

如果这是用作 db 中的主键字段,请考虑仅使用自动递增整数。

str(uuid.uuid4())是 36 个字符,但其中有四个无用的破折号 ( -),并且仅限于 0-9 af。

更好的 uuid4 32 个字符:

>>> uuid.uuid4().hex
'b327fc1b6a2343e48af311343fc3f5a8'
Run Code Online (Sandbox Code Playgroud)

或者只是 b64 编码和切片一些 urandom 字节(由您来保证唯一性):

>>> base64.b64encode(os.urandom(32))[:8]
b'iR4hZqs9'
Run Code Online (Sandbox Code Playgroud)

  • 必须有人指出 UUID4 可能在技术上发生冲突。(尽管可能性非常小。)[`uuid1`](https://docs.python.org/3.7/library/uuid.html#uuid.uuid1) 将“更独特”,因为它依赖于系统时间。也许这更符合这里的要求。 (2认同)