关于评论树:
1、评论信息在数据库中是以列表形式记录,其中至少包括当前评论id、父评论id(根评论id为null)、和评论内容,
2、在显示评论时,首先数据库中调取评论信息列表,列表中的每个元素对应一条评论信息字典,
3、将评论信息字典创建成有结构的评论树字典:build_tree
4、将评论树字典转换成html样式:tree
import collections,json # 将数据库中的普通字典列表,转换成有结构的评论树字典 def tree_search(comment_dic,comment_obj): for k,v_dic in comment_dic.items(): if json.loads(k)['nid'] == comment_obj['father_id']: comment_dic[k][json.dumps(comment_obj)] = collections.OrderedDict() return else: tree_search(comment_dic[k],comment_obj) def build_tree(comment_list): comment_dic = collections.OrderedDict() #有序字典 for comment_obj in comment_list: if comment_obj['father_id'] is 0: comment_dic[json.dumps(comment_obj)] = collections.OrderedDict() else: tree_search(comment_dic,comment_obj) return comment_dic #-------------------------------------------------- # 将有结构的评论树字典转换成html样式 # 注意:评论的全部子评论用ul表示,且一条评论是一个li,每个li中含有一个span显示评论的具体内容 TEMP1 = """ <li class="items" style='padding:8px 0 0 %spx;'> <span onclick="show_ul(this)"><a class="writer">%s:</a>%s<a class="time">--%s</a></span> <a class="reply" onclick="reply_comment(this,%s,%s)">回复</a> <a class="reply" onclick="delete_comment(this,%s,%s)">删除</a> <a class="reply">举报</a> """ def generate_comment_html(sub_comment_dict,margin_left_val): html = "<ul class='hide'>" for k,v_dic in sub_comment_dict.items(): key = json.loads(k) html += TEMP1 %(margin_left_val,key['writer'],key['content'],key['time'],key['nid'],key['news_id'],key['nid'],key['news_id']) if v_dic: html += generate_comment_html(v_dic,margin_left_val) html += "</li>" html += "</ul>" return html def tree(comment_tree): html = '' for k,v in comment_tree.items(): key = json.loads(k) html += TEMP1 %(0,key['writer'],key['content'],key['time'],key['nid'],key['news_id'],key['nid'],key['news_id']) html += generate_comment_html(v,16) html += "</li>" html += "<div class='xuxian'></div>" return html
class AccountHandler(BaseHandler):
def get(self):
# 获取数据库中指定新闻的评论信息
news_id = self.get_argument('news_id')
comment_info = account_info().get(news_id)
# print(comment_info)
# 创建评论树
comment_tree = build_tree(comment_info)
# print(comment_tree) # test
# 将评论树转化成html样式
comment_html = tree(comment_tree)
# print(comment_html) # test
self.write(json.dumps(comment_html))
5、添加新评论时,要记录新评论的父评论id
6、删除评论时,连带子评论一起删除
class AccountDelHandler(BaseHandler):
def __post_func(self,rep,post_info):
# 检查comment_id是否是当前用户,
if account_del().check_user(post_info['comment_id'],self.session['user']['user_id']):
# 将所有待删除的评论id放入一个列表
del_list = [int(post_info['comment_id']),]
# 提取指定news_id的所有评论的nid、father_id
ID_fatherID = account_del().id_father(post_info['news_id'])
# 将所有待删除的子评论id放入列表
for item in ID_fatherID:
if item['father_id'] in del_list:
del_list.append(item['nid'])
# 删除数据库中对应评论
account_del().remove(del_list)
rep.status = 1
else:
# 标识当前用户非评论发布者
rep.data = 1
return rep
浙公网安备 33010602011771号