1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
| import redis
class Comment(object):
"""创建评论"""
def __init__(self, client):
self.client = client
def create(self, author_id, content):
"""创建一条评论,并返回评论ID"""
comment_id = IdGenerator("weibo::comment::id", self.client).gen()
comment_key = "weibo::comment::" + str(comment_id)
self.client.hmset(comment_key, {"id": comment_id, "author_id": author_id, "time": int(time.time()), "content": content})
return comment_id
def get_by_id(self, comment_id):
"""获取指定ID的评论内容"""
comment_key = "weibo::comment::" + str(comment_id)
return self.client.hgetall(comment_key)
class CommentList(object):
"""将评论推入到该微博的评论列表中"""
def __init__(self, msg_id, client):
self.msg_id = msg_id
self.client = client
self.key = "weibo::message::" + str(msg_id) + "::comments"
def push(self, comment_id):
"""将评论ID推入到该微博的列表中"""
self.client.lpush(self.key, comment_id)
def count(self):
"""获取该微博的总评论数"""
return self.client.llen(self.key)
def paging(self, n):
"""查看第几页的评论,返回的是评论的ID"""
count = 5 # 5条评论为一页
start_index = (n-1) * count
end_index = n*count - 1
return self.client.lrange(self.key, start_index, end_index)
if __name__ == "__main__":
redis_client = redis.StrictRedis()
# 10010用户新写了一条微博
msg = Message(redis_client)
message_id, weibo_timestamp = msg.create(10010, "very nice day")
# 10086用户给这条微博做了评论
comment = Comment(redis_client)
comment_id = comment.create(10086, "very good")
# 将10086的这条评论推入到10010用户发布的微博的评论列表中
comment_list = CommentList(message_id, redis_client)
comment_list.push(comment_id)
# 获取这条微博的总评论数
print(comment_list.count())
# 查看该微博的第一页评论内容(ID)
print(comment_list.paging(1))
|