Files
Django/utils/invitationcode_utils.py
T

56 lines
1.6 KiB
Python

"""
阿龙电竞陪玩平台 - 邀请码生成工具
生成规则:毫秒时间戳 + 用户ID + 随机数 -> Base62编码 -> 固定20位邀请码
特点:唯一性高、生成快、无序不可读
"""
import time
import random
# Base62 编码字符集 (数字+小写字母+大写字母)
_BASE62_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
_BASE62_LENGTH = len(_BASE62_CHARS)
def base62_encode(num: int) -> str:
"""
将整数转换为 Base62 字符串,固定长度为 20 位
"""
if not num:
return _BASE62_CHARS[0]
res = []
while num:
num, r = divmod(num, _BASE62_LENGTH)
res.append(_BASE62_CHARS[r])
return ''.join(reversed(res))
def CreateInvitationCode(uid_str: str) -> str:
"""
创建唯一邀请码 (20位固定长度)
参数:
uid_str: 用户ID字符串,如 "123456"
返回:
str: 生成的唯一邀请码
"""
ts = int(time.time()*1000)
try:
uid = int(uid_str)
except ValueError:
uid = abs(hash(uid_str)) % 10**8
num = int(f"{ts}{uid:08d}{random.randint(0,9999):04d}")
res = base62_encode(num)
return res.rjust(20, _BASE62_CHARS[0]) if len(res)<20 else res[-20:]
def VerifyInvitationCode(yaoqingma: str) -> bool:
"""
验证邀请码是否有效 (简单的格式验证)
参数:
yaoqingma: 待验证的邀请码
返回:
bool: 邀请码格式是否有效
"""
return bool(yaoqingma and len(yaoqingma)==20 and all(c in _BASE62_CHARS for c in yaoqingma))