python的uuid都是32位的,比较长,处理起来效率比较低,
本算法利用62个可打印字符,通过随机生成32位UUID,由于UUID都为十六进制,所以将UUID分成8组,每4个为一组,然后通过模62操作,结果作为索引取出字符,
最后生成的Uuid,只有8位,代码如下:
uuid4,可以换成uuid1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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()) |
运行结果如下:
6vT7sxFK
F802Fj8C
s7E3qzmD
总结
以上所述是小编给大家介绍的Python生成短uuid的方法实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.cnblogs.com/xcr1234/archive/2018/05/29/9103461.html