comment.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from sql import db, 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, mysql: DB = db):
  6. """ 读取文章的 comment """
  7. cur = mysql.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 read_comment_list_iter(mysql: DB = db):
  15. """ 读取文章的 comment """
  16. cur = mysql.search("SELECT CommentID "
  17. "FROM comment_user "
  18. "ORDER BY UpdateTime DESC")
  19. if cur is None or cur.rowcount == 0:
  20. return []
  21. return cur
  22. def create_comment(blog_id: int, user_id: int, content: str, mysql: DB = db):
  23. """ 新建 comment """
  24. delete_user_comment_count_from_cache(user_id)
  25. cur = mysql.insert("INSERT INTO comment(BlogID, Auth, Content) "
  26. "VALUES (%s, %s, %s)", blog_id, user_id, content)
  27. if cur is None or cur.rowcount == 0:
  28. return False
  29. read_comment(cur.lastrowid, mysql) # 刷新缓存
  30. return True
  31. def read_comment(comment_id: int, mysql: DB = db, not_cache=False):
  32. """ 读取 comment """
  33. if not not_cache:
  34. res = get_comment_from_cache(comment_id)
  35. if res is not None:
  36. return res
  37. cur = mysql.search("SELECT BlogID, Email, Content, UpdateTime FROM comment_user WHERE CommentID=%s", comment_id)
  38. if cur is None or cur.rowcount == 0:
  39. return [-1, "", "", 0]
  40. res = cur.fetchone()
  41. write_comment_to_cache(comment_id, *res)
  42. return res
  43. def delete_comment(comment_id: int, mysql: DB = db):
  44. """ 删除评论 """
  45. delete_comment_from_cache(comment_id)
  46. delete_all_user_comment_count_from_cache()
  47. cur = mysql.delete("DELETE FROM comment WHERE ID=%s", comment_id)
  48. if cur is None or cur.rowcount == 0:
  49. return False
  50. return True
  51. def get_user_comment_count(user_id: int, mysql: DB = db, not_cache=False):
  52. """ 读取指定用户的 comment 个数 """
  53. if not not_cache:
  54. res = get_user_comment_count_from_cache(user_id)
  55. if res is not None:
  56. return res
  57. cur = mysql.search("SELECT COUNT(*) FROM comment WHERE Auth=%s", user_id)
  58. if cur is None or cur.rowcount == 0:
  59. return 0
  60. res = cur.fetchone()[0]
  61. write_user_comment_count_to_cache(user_id, res)
  62. return res