一个基于yeild的序列号生成器

主要用于短信或其他资源的ID映射
方法:

def get_format(max_int = 1000000,from_int = 0,min_length = 5):
    def f(n):
        chars = "abcdefghigklmnopqrstuvwxyz".upper()
        b=[]
        x = len(chars)
        while True:
            s=n//x  # 商
            y=n%x  # 余数
            b.append(y)
            if s==0:
                break
            n=s
        b.reverse()
        re_str  = ""
        for i in b:
            re_str = re_str + (chars[i])
        return re_str
    while from_int <= max_int:
        re_str = f(from_int)
        if len(re_str) < min_length:
            for i in range(min_length - len(f(from_int)) ):
                re_str = re_str + str(int(random.random()*10))
        # 增加校验位
        re_str = re_str + (hashlib.md5(re_str.encode(encoding='UTF-8')).hexdigest()[0:1])
        yield re_str
        from_int = from_int + 1

使用

auto_id = get_format()
auto_id.__next__()

附带:加密解密方法

def decrypt_format(str_val):
    chars = "abcdefghigklmnopqrstuvwxyz".upper()
    x = len(chars)

    short_str= ""
    for i in str_val:
        if i in chars:
            short_str = short_str + i
    # 计算数量
    re_int = 0
    y = 0
    for c in reversed(short_str):
        inx = chars.find(c)
        re_int = re_int + math.pow( x, y ) * inx
        y = y + 1
        
    return int(re_int)




def encrypt_format(int_n,min_length = 5):
    def f(n):
        chars = "abcdefghigklmnopqrstuvwxyz".upper()
        b=[]
        x = len(chars)
        while True:
            s=n//x  # 商
            y=n%x  # 余数
            b.append(y)
            if s==0:
                break
            n=s
        b.reverse()
        re_str  = ""
        for i in b:
            re_str = re_str + (chars[i])
        return re_str

    re_str = f(int_n)
    if len(re_str) < min_length:
        for i in range(min_length - len(re_str) ):
            re_str = re_str + str(int(random.random()*10))
    # 增加校验位
    re_str = re_str + (hashlib.md5(re_str.encode(encoding='UTF-8')).hexdigest()[0:1]).lower()
    return re_str

执行:

print(decrypt_format('BL4028')) #37
print(encrypt_format(decrypt_format('BL4028'))) #BL775f
print(decrypt_format(encrypt_format(decrypt_format('BL4028')))) #37

你可能感兴趣的:(一个基于yeild的序列号生成器)