头歌 初识Redis

第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 交互

#!/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 *********#

第3关:使用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

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值