首页 > 代码库 > Redis之网站文章投票

Redis之网站文章投票

直接上代码:

# python3
# -*- coding: utf-8 -*-

import redis
import time

ONE_WEEK_IN_SECONDS = 7 * 86400
# 如果一篇文章获得200个赞,那么这篇文章就是有趣的
VOTE_SCORE = 86400 / 200

def redis_init(redis):
    # article_time记录文章发布时间
    redis.zadd(article_time, article_100408=1496662197, article_100635=1496669721, article_100716=1496660089)
    # article_score记录文章得分
    redis.zadd(article_score, article_100408=1496666517, article_100635=1496670153, article_100716=1496665705)
    # voted_article_id记录编号为article_id的文章的点赞用户集合
    redis.sadd(voted_100408, user_234487, user_253378, user_364680,
               user_132097, user_350917)
    # 用hash描述每篇文章
    article_desc = {title:kunlun, link:www.kunlun.com, poster:fengge, time:1441728000, votes:523}
    redis.hmset(article_100408, article_desc)
    article_desc = {title: zhuxian, link: www.zhuxian.com, poster: xiaoding, time: 1081440000, votes: 677}
    redis.hmset(article_100635, article_desc)
    article_desc = {title: soushenji, link: www.soushenji.com, poster: shuxiayehu,
                    time: 1187280000, votes: 421}
    redis.hmset(article_100635, article_desc)

def article_note(conn, user, article):
    cutoff = time.time() - ONE_WEEK_IN_SECONDS
    if conn.zscore(article_time, article) < cutoff:
        return

    article_id = article.partition(_)[-1]
    if conn.sadd(voted_ + article_id, user):
        conn.zincrby(article_score, article, VOTE_SCORE)
        conn.hincrby(article, votes, 1)


r = redis.StrictRedis(host=redis_server_ip, port=6379, password=redis_passwd, db=0)
redis_init(r)
article_note(r,use_115423, article_100408)

 

参考资料:

《Redis实战》

Redis之网站文章投票