本题的链接来自https://github.com/Yixiaohan/show-me-the-code

0001题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。

解析

对于我来说MySQL还是挺熟悉的,但对于Redis还是很不熟悉。所以Redis的安装还是头疼的,加之网上也有很多网友安装Redis也出现了很多错误,所以在此,给大家推荐一个安装Redis的教程在windows下安装Redis还有一个就是对于Redis的基本操作教程,Redis的基本操作Redis官方文档

这题是要生成激活码这个在我的另外一篇博客里有,Python 练习册0001

代码

#coding:utf-8
import redis
import uuid
def generate(): #生成激活码
    li = []
    for i in range(200):  # 生成200个
        while (True):
            s = str(uuid.uuid4()).replace('-','')
            if not s in li:  # 判断生成的uuid是否存在于之前的序列中,如果存在重新生成
                li.append(s)
                break
    return li
def insert_sql(): #将激活码放入数据库
    codes = generate()
    re = redis.Redis(host = "localhost", port = 6379,db = 0) #连接redis数据库
    for co in codes: #写入数据库
        re.lpush('code',co)

if __name__ == '__main__':
    insert_sql()