question No. 0003: Save the 200 activation codes (or coupons) generated by 0001 questions to the Redis non-relational database.
Similar to the 0002 question, it is just the exchange of relational databases with non-relational databases.
Steps:
- Install Redis and libraries first, install with PIP
- Open Radis Server
- Then understand the operation of Redis
- Introducing the library into your code
- Connect to a database, write data, save
Python is very convenient to connect to Redis, and the operation is similar to REDIS-CLI.
Since the generated activation code should be non-repeatable, I chose to save it using the set data structure.
Common operations for Redis set data types are:
- Sadd Key member inserts a member member into the collection, returning the actually inserted member
- Smembers Key gets all the members in the set associated with the key.
- Sismember Key member checks if member is a member of the collection key. Return 1
- SCard Key gets the number of members in key
0003.Redis operation. py
#!/usr/bin/env python#coding: utf-8import redisimport gennerate_codeHOST = ‘localhost‘6379#连接到数据库r = redis.Redis(HOST,PORT)#生成200组激活码codelist = gennerate_code.generate(200)#将生成的激活码存入数据库中for i in xrange(200): r.sadd("code",codelist[i])r.save()
Where Gennerate_code is the code in the Python show-me-the-code No. 0001 generating the activation code
Python show-me-the-code question No. 0003 Redis operation