第1关:Redis中的数据结构
redis-cli
set hello redis
lpush educoder-list hello
rpush educoder-list educoder
rpush educoder-list bye
rpop educoder-list
sadd educoder-set c
sadd educoder-set python
sadd educoder-set redis
srem educoder-set c
hset educoder-hash python language
hset educoder-hash ruby language
hset educoder-hash redis database
hdel educoder-hash ruby
zadd educoder-zset 200 jack
zadd educoder-zset 400 rose
zadd educoder-zset 100 lee
————————————————
版权声明:本文为CSDN博主「南风不竞呀」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_56494324/article/details/124167105
第2关:使用 Python 与 Redis 交互
import redis
def write_redis():
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True)
r1 = redis.Redis(connection_pool=pool)
r1.set("test1", "hello")
r1.set("test2", "Redis")
第3关:使用Python+Redis实现文章投票网站后端功能
import time
ONE_WEEK_IN_SECONDS = 7 * 24 * 60 * 60
def article_vote(r, user_id, article_id):
cutoff = time.time() - ONE_WEEK_IN_SECONDS
cutoff = time.time() - ONE_WEEK_IN_SECONDS
if r.zscore('time', article_id) < cutoff:
return
if r.sadd('voted:' + article_id, user_id):
r.zincrby('score', article_id, 1)
def post_article(r, user, title, link):
article_id = str(r.incr('article'))
voted = 'voted:' + article_id
r.sadd(voted, user)
r.expire(voted, ONE_WEEK_IN_SECONDS)
now = time.time()
article = 'article:' + article_id
r.hmset(article, {
'title': title,
'link': link,
'poster': user,
})
r.zadd('score', article_id, 1)
r.zadd('time', article_id, now)
return article_id
def get_articles(r, start, end, order='score'):
articles = []
ids = r.zrevrange(order, start, end)
for id in ids:
article_data = r.hgetall(id)
article_data['id'] = id
articles.append(article_data)
return articles