实现用户微博个人时间线和定制时间线:

imprort redis

class TimeLine(object):
    """用户定制时间线和个人时间线"""
    def __init__(self, client):
        self.client = client
        
    def custom_push(self, user_id, msg_id, time):
        """将微博推入到用户定制的时间线中"""
        custom_timeline_key = "weibo::user::" + str(user_id) + "::custom_timeline"
        self.client.zadd(custom_timeline_key, time, msg_id)
        
    def personal_push(self, user_id, msg_id, time):
        """将微博推入到用户的个人时间线中"""
        personal_timeline_key = "weibo::user::" + str(user_id) + "::personal_timeline"
        self.client.zadd(personal_timeline_key, time, msg_id)
        
    def broadcast(msg_id, time, *fans_ids):
        """将微博推入所有粉丝的定制时间线中"""
        for fans in fans_ids:
            self.custom_push(fans, msg_id, time)
        
    def custom_paging(self, user_id, n):
        """获取用户定制时间线第n页的微博"""
        count = 5  # 5条数据为一页
        custom_timeline_key = "weibo::user::" + str(user_id) + "::custom_timeline"
        start_index = (n-1) * count  # 起始索引
        end_index = n*count - 1  # 结束索引
        return self.client.zrevrange(custom_timeline_key, start_index, end_index)
        
    def personal_paging(self, user_id, n):
        """获取用户个人时间线第n页的微博"""
        count = 5  # 5条数据为一页
        personal_timeline_key = "weibo::user::" + str(user_id) + "::personal_timeline"
        start_index = (n-1) * count  # 起始索引
        end_index = n*count - 1  # 结束索引
        return self.client.zrevrange(personal_timeline_key, start_index, end_index)


if __name__ == "__main__":
  redis_client = redis.StrictRedis()        
  msg = Message(redis_client)
  message_id, weibo_timestamp = msg.create(10086, "hello world")
  # print("message_id:", message_id)
  # print("weibo_timestamp:", weibo_timestamp)

  tl = TimeLine(redis_client)
  tl.custom_push(10086, message_id, weibo_timestamp)
  tl.personal_push(10086, message_id, weibo_timestamp)

  relation = RelatoinShip(redis_client)
  fans_dict = relation.get_all_fans(10086)
  if fans_dict == False:
      print("没有粉丝")
  else:
      fans_list = list()
      for fans in fans_dict:
          fans_list.append(fans.decode())
      tl.broadcast(message_id, weibo_timestamp, *fans_list)
        
  print(tl.custom_paging(10086, 1))
  print(tl.personal_paging(10086, 1))

    什么是用户个人的微博时间线和定制的微博时间线呢?用户微博定制时间线包含了用户自己以及用户正在关注的人所发布的微博,我们用"weibo::user::<id>::custom_timeline"这个有序集合键保存;用户个人微博时间线,只包含用户自己发送的微博,我们用"weibo::user::<id>::personal_timeline"这个有序集合键保存。

        每条时间线都是一个有序集合,有序集合的元素是所发布微博的ID,分值为微博发布的时间。每当用户发送新的微博时,redis用zadd将新微博的时间和id添加到有序集合中。

        当然我们不能漏了广播操作,即每当用户发送一条新的微博时,redis不仅要将这条微博推入该用户的定制时间线和个人时间线,还需要将这条微博推入到该用户的所有粉丝的定制时间线中。

        在上面的代码中,我们使用了之前已经定义好的Message类来生成一条微博消息,再使用RelationShip类来实现向所有的粉丝的定制时间线推送微博信息。