我想在我的网站上为用户生成一个大小为5的字符串(密钥),类似于BBM PIN。
该密钥将包含数字和大写英文字母:
- AU1B7
- Y56AX
- M0K7A
即使我生成数百万个字符串,我也希望能够放心地保证其唯一性。
请问最Pythonic的方法是什么?
这里提供一种生成长度为5或任意长度代码的解决方案:
import shortuuid as su
n = int(input("# codes to gen: "))
l = int(input("code lenght: "))
shou = su.ShortUUID(alphabet="QWERTYUIOPASDFGHJKLZXCVBNM0123456789")
codes = set()
LEN_CNT = 0
with open('file.txt', 'w') as file:
while len(codes) < n:
cd = shou.random(length=l)
codes.add(cd)
if len(codes) > LEN_CNT:
LEN_CNT = len(codes)
file.write(f"{cd}\n")
base64.b32encode('12345') == 'GEZDGNBV'
- Paulo Scardinedjango.utils.crypto.get_random_string(5, string.ascii_uppercase+string.digits)
生成它们。您可能希望限制字符集,以避免生成可能在某些字体中难以辨认的混淆字符串,例如l1I1l
。唯一性需要您持久化分配的字符串集合。 - mhawke