Example of Python generating short uuid is explained in detail

  • 2020-10-23 21:04:20
  • OfStack

The uuid of python is 32-bit, which is longer and less efficient to process.

This algorithm USES 62 printable characters to generate 32-bit UUID randomly. Since all UUID are based on decimal 106, it divides UUID into 8 groups, each of which is 1 group. Then, it performs mode 62 operation and extracts characters as indexes.

Finally, Uuid is generated with only 8 bits. The code is as follows:

uuid4 can be replaced by uuid1


from uuid import uuid4
uuidChars = ("a", "b", "c", "d", "e", "f",
       "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
       "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
       "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
       "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
       "W", "X", "Y", "Z")
def short_uuid():
  uuid = str(uuid4()).replace('-', '')
  result = ''
  for i in range(0,8):
    sub = uuid[i * 4: i * 4 + 4]
    x = int(sub,16)
    result += uuidChars[x % 0x3E]
  return result
print(short_uuid())
print(short_uuid())
print(short_uuid())

The operation results are as follows:

[

6vT7sxFK
F802Fj8C
s7E3qzmD

]

conclusion


Related articles: