Python 練習冊,每天一個小程序,原題來自Yixiaohan/show-me-the-code
我的代碼倉庫在Github
目標
做為 Apple Store App 獨立開發(fā)者,你要搞限時促銷,為你的應用生成激活碼(或者優(yōu)惠券),使用 Python 生成 200 個激活碼(或者優(yōu)惠券),并將激活碼保存到 Redis 非關系型數(shù)據(jù)庫中。
解決方案
該題目采用 python 中的 Redis
模塊 來連接操作Redis
數(shù)據(jù)庫,代碼如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 將0001題目中隨機生成的驗證碼保存到Redis 數(shù)據(jù)庫
import uuid
import redis
# 生成 num 個驗證碼,每個長度為length,可設置默認長度
def create_num(num, length=16):
result = []
while num > 0:
uuid_id = uuid.uuid4()
# 刪去字符串中的'-',取出前l(fā)ength 個字符
temp = str(uuid_id).replace('-', '')[:length]
if temp not in result:
result.append(temp)
num -= 1
return result
# 保存到Redis數(shù)據(jù)庫
def save_to_redis(num_list):
r = redis.Redis(host='localhost', port=6379, db=0)
for code in num_list:
r.lpush('code', code)
save_to_redis(create_num(200))