Python 练习册,每天一个小程序,原题来自Yixiaohan/show-me-the-code
我的代码仓库在Github

目标

做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 生成 200 个激活码(或者优惠券),并将激活码保存到 Redis 非关系型数据库中。

解决方案

该题目采用 python 中的 Redis 模块 来连接操作Redis数据库,代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


# 将0001题目中随机生成的验证码保存到Redis 数据库
import uuid
import redis


# 生成 num 个验证码,每个长度为length,可设置默认长度
def create_num(num, length=16):
    result = []
    while num > 0:
        uuid_id = uuid.uuid4()
        # 删去字符串中的\'-\',取出前length 个字符
        temp = str(uuid_id).replace(\'-\', \'\')[:length]
        if temp not in result:
            result.append(temp)
            num -= 1
    return result


# 保存到Redis数据库
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))