首页 > 代码库 > Hello Redis - Voting on articles

Hello Redis - Voting on articles

Redis in Action JOSIAH L. CARLSON MANNING Shelter Island

 1 ONE_WEEK_IN_SECONDS = 7 * 86400 2 VOTE_SCORE = 432 3  4 def article_vote(conn, user, article): 5     cutoff = time.time() - ONE_WEEK_IN_SECONDS 6     if conn.zscore(time:, article) < cutoff: 7         return 8  9     article_id = article.partition(:)[-1]10     if conn.sadd(voted: + article_id, user):11         conn.zincrby(score:, article, VOTE_SCORE)12         conn.hincrby(article, votes, 1)13 14 def post_article(conn, user, title, link):15     article_id = str(conn.incr(article:))16 17     voted = voted: + article_id18     conn.sadd(voted, user)19     conn.expire(voted, ONE_WEEK_IN_SECONDS)20 21     now = time.time()22     article = article: + article_id23     conn.hmset(article, {24             title: title,25             link: link,26             poster: user,27             timer: now,28             votes:1,29         })30 31     conn.zadd(score:, article, now + VOTE_SCORE)32     conn.zadd(time:, article, now)33 34     return article_id35 36 37 ARTICLES_PER_PAGE = 2538 39 def get_articles(conn, page, order=score:):40     start = (page-1) * ARTICLES_PER_PAGE41     end = start + ARTICLES_PER_PAGE - 142 43     ids = conn.zrevrange(order, start, end)44     articles = []45     for id in ids:46         article_data =http://www.mamicode.com/ conn.hgetall(id)47         article_data[id] = id48         articles.append(article_data)49 50     return articles

 

 1 def add_remove_groups(conn, article_id, to_add=[], to_remove=[]): 2     article = article: + article_id 3     for group in to_add: 4         conn.sadd(group: + group, article) 5     for group in to_remove: 6         conn.srem(group: + group, article) 7  8 def get_group_articles(conn, group, page, order=score:): 9     key = order + group10     if not conn.exists(key):11         conn.zinterstore(key,12             [group: + group, order],13             aggregate = max,14         )15         conn.expire(key, 60)16     return get_articles(conn, page, key)

 

Hello Redis - Voting on articles