原GitHub地址:https://github.com/Yixiaohan/show-me-the-code
题目:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。
代码:
import uuid
import redis
# 生成激活码,number为数量,length为长度
def generate_code(number, length):
codes = []
k = 0
while(True):
temp = str(uuid.uuid1()).replace("-", "")[:length]
if k == number:
break
elif temp not in codes:
codes.append(temp)
k += 1
else:
continue
return codes
# 插入数据库
def insert_into_redis(codes):
r = redis.Redis(host='127.0.0.1', port=6379, decode_responses=True)
counter = 0
for code in codes:
r.set('code-%s' % counter, code)
counter += 1
print(r.get('code-0'))
if __name__ == '__main__':
codes = generate_code(20, 12)
insert_into_redis(codes)