(七)redis实战1

参考:

  • redis in action
import time
import redis

ONE_WEAK_IN_SECONDS=7*86400
VOTE_SCORE=432

def article_vote(conn, user, article):
    cutoff=time.time()-ONE_WEAK_IN_SECONDS
    if conn.zscore('time:',article)<cutoff:
        return
    article_id=article.partition(':')[-1]
    if conn.sadd('voted:'+article_id,user):
        conn.zincrby('score:',article,VOTE_SCORE)
        conn.hincrby(article,'votes',1)


def post_aiticle(conn, title, id, user):
    voted = "voted:"+id
    conn.sadd(voted,user)
    conn.expire(voted,ONE_WEAK_IN_SECONDS)

    now = time.time()
    article = "article:" + id
    conn.hmset(article,{
        'title':title,
        'time':now,
        'votes':1,
        'poster':user
    })
    conn.zadd('score:',{article:now+VOTE_SCORE})
    conn.zadd('time:',{article:now})

def test():
    conn=redis.Redis('localhost',6379,0)
    user='caicai'
    article='english'
    id="3327"
    post_aiticle(conn,article,id,user)
    post_aiticle(conn,'chinese',"3386",'pipi')


test()
posted @ 2019-01-10 00:53  yvhqbat  阅读(119)  评论(0编辑  收藏  举报