基于Python生成短8位唯一id解決方案
by:授客 QQ:1033553122
測驗環境:
Win10
Python 3.5.4
實作思路
利用62個可列印字符,通過隨機生成32位UUID,由于UUID都為十六進制,所以將UUID分成8組,每4個為一組,然后通過模62(字符0-9,a-z,A-Z總數量62個字符)操作,結果作為索引取出字符,這樣重復率大大降低,實踐測驗,運行20000000次,僅出現2個重復id(僅測驗過一次),
當然,這樣還達不到唯一id,因為還是有重復的,解決方法呢,可以考慮結合資料庫、或者其它存盤來實作,以結合資料庫為例,我們可以新建一張資料庫表,并給表設定一個id欄位,并且設定為主鍵、或者增加唯一約束,每次獲取8 id后,往表里插入一條資料,如果可以成功插入,說明不重復,否則說明是重復id,再次嘗試獲取,
核心代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@CreateTime: 2020/07/14 11:04
@Author : shouke
'''
import uuid
array = [ "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",
"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 get_short_id():
id = str(uuid.uuid4()).replace("-", '') # 注意這里需要用uuid4
buffer = []
for i in range(0, 8):
start = i * 4
end = i * 4 + 4
val = int(id[start:end], 16)
buffer.append(array[val % 62])
return "".join(buffer)
測驗驗證
id_set = set() # 用于存放生成的唯一id
count = 0 # 用于統計出現重復的次數
index = [] # 記錄第幾次呼叫生成8位id出現重復
for i in range(0, 20000000):
id = get_short_id()
if id in id_set:
count += 1
index.append(str(i+1))
else:
id_set.add(id)
print('id:%s, 運行第 %s 次, 重復數:%s , 重復率:%s, 出現重復次序 %s' % (id, i+1, count, count/(i+1)*100, ','.join(index)))

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/69438.html
標籤:Python
