comment.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from sql import db
  2. from sql.cache import (get_comment_from_cache, write_comment_to_cache, delete_comment_from_cache,
  3. get_user_comment_count_from_cache, write_user_comment_count_to_cache,
  4. delete_all_user_comment_count_from_cache, delete_user_comment_count_from_cache)
  5. def read_comment_list(blog_id: int):
  6. """ 读取文章的 comment """
  7. cur = db.search("SELECT CommentID "
  8. "FROM comment_user "
  9. "WHERE BlogID=%s "
  10. "ORDER BY UpdateTime DESC", blog_id)
  11. if cur is None or cur.rowcount == 0:
  12. return []
  13. return [i[0] for i in cur.fetchall()]
  14. def create_comment(blog_id: int, user_id: int, content: str):
  15. """ 新建 comment """
  16. delete_user_comment_count_from_cache(user_id)
  17. content = content.replace("'", "''")
  18. cur = db.insert("INSERT INTO comment(BlogID, Auth, Content) "
  19. "VALUES (%s, %s, %s)", blog_id, user_id, content)
  20. if cur is None or cur.rowcount == 0:
  21. return False
  22. return True
  23. def read_comment(comment_id: int):
  24. """ 读取 comment """
  25. res = get_comment_from_cache(comment_id)
  26. if res is not None:
  27. return res
  28. cur = db.search("SELECT BlogID, Email, Content, UpdateTime FROM comment_user WHERE CommentID=%s", comment_id)
  29. if cur is None or cur.rowcount == 0:
  30. return [-1, "", "", 0]
  31. res = cur.fetchone()
  32. write_comment_to_cache(comment_id, *res)
  33. return res
  34. def delete_comment(comment_id):
  35. """ 删除评论 """
  36. delete_comment_from_cache(comment_id)
  37. delete_all_user_comment_count_from_cache()
  38. cur = db.delete("DELETE FROM comment WHERE ID=%s", comment_id)
  39. if cur is None or cur.rowcount == 0:
  40. return False
  41. return True
  42. def get_user_comment_count(user_id: int):
  43. """ 读取指定用户的 comment 个数 """
  44. cur = db.search("SELECT COUNT(*) FROM comment WHERE Auth=%s", user_id)
  45. if cur is None or cur.rowcount == 0:
  46. return 0
  47. return cur.fetchone()[0]