【python案例】批量生成可逆转的优惠券
我们再做电商的时候,经常要生成优惠券这些的东西。
要简单点,随便随机一些不重复的字符串就可以了。
但是有时候我们需要根据单个产品来生产优惠券,又可以根据优惠券找出这个产品ID。
这就是我们所说的可逆转的解码和编码。
首先我们来看看代码。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import base64
# base64编码方便使用
# 通过id检验优惠券是否存在,通过goods查找商品
coupon = {
'id': '1000',
'goods': '500',
}
def gen_coupon(id, goods):
coupon['id'] = id
coupon['goods'] = goods
raw = ','.join([k + ':' + v for k, v in coupon.items()])
raw_64 = base64.urlsafe_b64encode(raw.encode('utf-8'))
c_code = raw_64.decode()
return c_code
def save_coupon(c_code):
with open('coupon.txt', 'a+') as file:
file.write(c_code+'\n')
def show_coupon(c_code):
print('优惠码:', c_code)
def parse_coupon(c_code):
print('解析优惠码:', base64.urlsafe_b64decode(c_code.encode('utf-8')))
def gen_all():
for i in range(1000, 1200):
c_code = gen_coupon(str(i), str(int(i/2)))
save_coupon(c_code)
if __name__ == '__main__':
gen_all()
这里我们用了base64.urlsafe_b64encode来生成编码。
用 raw = ‘,’.join([k + ‘:’ + v for k, v in coupon.items()])把id和goods组合到一起,这样子的格式:id:1000,goods:500
我们来运行这段python代码,看看目录文件下生成的优惠码。

【python案例】运用PIL在图片加上数字水印的方法 【python案例】将生成的优惠券放入到mysql中
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://www.binance.info/register?ref=P9L9FQKY