Skip to content

Commit c214d81

Browse files
committed
modified my python file
1 parent 9970e41 commit c214d81

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

GenerateUniqueCode.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import random
2+
import string
3+
"""
4+
主键+随机码的方式:
5+
6+
优点:使用也比较简单,不用直接去查询数据库,而最大的优点是查询的时候,可以根据邀请码直接得到主键id, 然后根据id去数据库查询(速度很快),再比较查询出来的邀请码和用户提交的邀请码是否一致。
7+
"""
8+
9+
10+
def create_code(id, length=12):
11+
"""
12+
组成:id(数据库primary key )->16进制 + "L(标识符)" +随机码
13+
14+
:param id: DB主键
15+
:param length: 随机码的长度
16+
"""
17+
prefix = hex(int(id))[2:] + 'L' # 因为16进制数前两位均为0x,只是标识,所以从2切片,其中'L'是业务标识符
18+
length -= len(prefix)
19+
chars = string.ascii_letters + string.digits # 所有的大小写字母和数字
20+
return prefix + ''.join([random.choice(chars) for i in range(length)]) # 将前缀与随机字符串进行拼接
21+
22+
23+
def get_id(code):
24+
""" 将16进制的id再转回10进制 """
25+
return str(int(code.upper(), 16))
26+
27+
28+
if __name__ == "__main__":
29+
for i in range(10, 500, 35):
30+
code = create_code(i)
31+
id_hex = code.split('L')[0]
32+
id = get_id(id_hex)
33+
print(code, id) # 输出唯一随机码和DB的主键Id

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,8 @@ The following code is something really useful.
2424

2525
**【011】HandleXML.py——处理XML数据**
2626

27+
**【012】GenerateUniqueCode.py——生成唯一随机码(可作为优惠券或验证码等)**
28+
29+
2730

2831
......持续更新中

0 commit comments

Comments
 (0)