初识Redis educoder
第1关:Redis中的数据结构redis-cliset hello redislpush educoder-list hellorpush educoder-list educoderrpush educoder-list byerpop educoder-listsadd educoder-set csadd educoder-setpythonsrem chset educoder-hash
·
第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
第二关:使用Python与Redis交互
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import redis
def write_redis():
#********* Begin *********#
# 创建连接池
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True)
# 创建客户端并连接到 Redis
r1 = redis.Redis(connection_pool=pool)
r1.set("test1", "hello")
r1.set("test2", "Redis")
#********* End *********#
第三关:使用Python+Redis实现文章投票网站后端功能
#!/usr/bin/env python #-*- coding:utf-8 -*- 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 # 请在下面完成要求的功能 #********* Begin *********# 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) #********* End *********# 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 # 请在下面完成要求的功能 #********* Begin *********# r.hmset(article, { 'title': title, 'link': link, 'poster': user, }) r.zadd('score', article_id, 1) r.zadd('time', article_id, now) #********* End *********# return article_id def get_articles(r, start, end, order='score'): articles = [] ids = r.zrevrange(order, start, end) # 请在下面完成要求的功能 #********* Begin *********# for id in ids: article_data = r.hgetall(id) article_data['id'] = id articles.append(article_data) #********* End *********# return articles
更多推荐
已为社区贡献3条内容
所有评论(0)