You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

176 lines
7.2 KiB

8 months ago
8 months ago
9 months ago
10 months ago
8 months ago
8 months ago
9 months ago
10 months ago
8 months ago
8 months ago
9 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
10 months ago
8 months ago
10 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
10 months ago
9 months ago
8 months ago
10 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
10 months ago
10 months ago
8 months ago
10 months ago
9 months ago
10 months ago
10 months ago
8 months ago
10 months ago
8 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
10 months ago
8 months ago
8 months ago
8 months ago
10 months ago
10 months ago
9 months ago
10 months ago
8 months ago
10 months ago
8 months ago
10 months ago
10 months ago
10 months ago
9 months ago
8 months ago
9 months ago
10 months ago
10 months ago
8 months ago
10 months ago
9 months ago
10 months ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
8 months ago
9 months ago
  1. from fastapi import Depends, APIRouter, Query, Path,Request
  2. from internal.models import *
  3. from datetime import date
  4. from internal.database import (
  5. fetch_one,
  6. fetch_all,
  7. execute_query,
  8. response_success,
  9. raise_if_exists,
  10. raise_if_not_found,
  11. )
  12. from dependencies import get_current_active_user
  13. import json
  14. from limiter_config import limiter
  15. router = APIRouter(prefix="/blogs", tags=["博客管理"])
  16. # 获取列表
  17. @router.get("/list")
  18. @limiter.limit("5/minute")
  19. async def blog_list(request: Request,page: int = Query(None), page_size: int = Query(None)):
  20. limit_clause = ""
  21. if page is not None and page_size is not None:
  22. offset = (page - 1) * page_size
  23. limit_clause = f"LIMIT {page_size} OFFSET {offset}"
  24. # 列表参数:博客名称、博客内容、创建时间、博客图片、博客查看时间、博客阅读次数、博客字数、类型名称、标签名列表
  25. select_query = f"""
  26. SELECT blogs.id,blogs.blogtitle, blogs.blogcontent, blogs.create_at, blogs.imglink,
  27. blogs.wordcount, blogtypes.typename,JSON_ARRAYAGG(labels.labelname) AS labelnames
  28. FROM blogs
  29. LEFT JOIN `blogtypes` ON blogs.typeid = blogtypes.id
  30. LEFT JOIN blog_label ON blog_label.blogid = blogs.id
  31. LEFT JOIN labels ON blog_label.labelid = labels.id
  32. GROUP BY blogs.id, blogs.blogtitle, blogs.blogcontent, blogs.create_at, blogs.imglink,
  33. blogs.wordcount, blogtypes.typename ORDER BY create_at DESC
  34. {limit_clause};
  35. """
  36. blog_list = fetch_all(select_query)
  37. count_query = "SELECT COUNT(*) AS total FROM blogs;"
  38. total_records = fetch_one(count_query)["total"]
  39. return response_success({
  40. "blogs": blog_list,
  41. "total": total_records,
  42. }, "blog get list success")
  43. @router.get("/list/{id}")
  44. @limiter.limit("5/minute")
  45. async def blog_one(request:Request,id: int):
  46. # 列表参数:博客名称、博客内容、创建时间、博客图片、博客查看时间、博客阅读次数、博客字数、类型名称、标签名列表
  47. select_query = """
  48. SELECT id, blogtitle, blogcontent FROM blogs
  49. WHERE id = %s
  50. ORDER BY create_at DESC;
  51. """
  52. blog_one = fetch_one(select_query, (id,))
  53. return response_success(blog_one, "blog get blog_one success")
  54. # 博客新增
  55. @router.post("/add")
  56. @limiter.limit("5/minute")
  57. async def blog_add(request:Request,blog: Blog, labels: list[Label], _: User = Depends(get_current_active_user)):
  58. select_query = "SELECT * FROM blogs WHERE blogtitle = %s"
  59. existing_blog = fetch_one(select_query, (blog.blogtitle,))
  60. raise_if_exists(existing_blog, "Blog already exists")
  61. insert_query = (
  62. "INSERT INTO blogs (blogtitle, blogcontent,imglink, typeid, descr) VALUES (%s, %s, %s, %s,%s)"
  63. )
  64. insert_data = (blog.blogtitle, blog.blogcontent,
  65. blog.imglink, blog.typeid, blog.descr)
  66. blog_id = execute_query(insert_query, insert_data, lastrowid=True)
  67. for label in labels:
  68. insert_label_query = "INSERT INTO blog_label (blogid, labelid) VALUES (%s, %s)"
  69. execute_query(insert_label_query, (blog_id, label.id))
  70. return {"message": "Blog created successfully", "blog_id": blog_id}
  71. # 博客删除
  72. @router.delete("/delete/{id}")
  73. @limiter.limit("5/minute")
  74. async def blog_delete(request:Request,id: str = Path(description="博客id")):
  75. select_query = "SELECT * FROM blogs WHERE id = %s"
  76. existing_blog = fetch_one(select_query, (id,))
  77. raise_if_not_found(existing_blog, "blog not found")
  78. insert_query = "DELETE FROM blogs WHERE id = %s"
  79. execute_query(insert_query, (id,))
  80. return response_success(message="blog delete success")
  81. @router.put("/update/{id}")
  82. @limiter.limit("5/minute")
  83. async def blog_update(request:Request,id: int, blog: Blog, labels: list[Label], _: User = Depends(get_current_active_user)):
  84. # 检查要编辑的博客是否存在
  85. select_query = "SELECT * FROM blogs WHERE id = %s"
  86. existing_blog = fetch_one(select_query, (id,))
  87. raise_if_not_found(existing_blog, "blog not found")
  88. # 更新博客信息
  89. update_query = (
  90. "UPDATE blogs SET blogtitle = %s, blogcontent = %s, imglink = %s, typeid = %s, descr = %s WHERE id = %s"
  91. )
  92. update_data = (blog.blogtitle, blog.blogcontent,
  93. blog.imglink, blog.typeid, blog.descr, id)
  94. execute_query(update_query, update_data)
  95. # 首先删除原有的关联标签
  96. delete_query = "DELETE FROM blog_label WHERE blogid = %s"
  97. execute_query(delete_query, (id,))
  98. # 然后插入新的关联标签
  99. for label in labels:
  100. insert_label_query = "INSERT INTO blog_label (blogid, labelid) VALUES (%s, %s)"
  101. execute_query(insert_label_query, (id, label.id))
  102. return response_success("blog update sucess")
  103. # 博客模糊查询
  104. @router.get("/search")
  105. @limiter.limit("5/minute")
  106. async def blog_list_search(
  107. request:Request,
  108. blogtitle: str = Query(None, description="博客标题"),
  109. typename: str = Query(None, description="博客类型"),
  110. start_date: str = Query(None, description="开始时间"),
  111. end_date: str = Query(None, description="结束时间"),
  112. ):
  113. select_query = """
  114. SELECT blogs.id, blogtitle, blogcontent,wordcount, typename, create_at, update_at, blogs.descr,JSON_ARRAYAGG(labels.labelname) AS labelnames
  115. FROM blogs
  116. LEFT JOIN `blogtypes` ON blogs.typeid = blogtypes.id
  117. LEFT JOIN blog_label ON blogs.id = blog_label.blogid
  118. LEFT JOIN labels ON blog_label.labelid = labels.id
  119. WHERE 1=1
  120. """
  121. params = []
  122. if blogtitle:
  123. select_query += " AND blogtitle LIKE %s"
  124. params.append(f"%{blogtitle}%")
  125. if typename:
  126. select_query += " AND typename LIKE %s"
  127. params.append(f"%{typename}%")
  128. if start_date:
  129. select_query += " AND create_at >= %s"
  130. params.append(start_date)
  131. if end_date:
  132. select_query += " AND create_at <= %s"
  133. params.append(end_date)
  134. select_query += "GROUP BY blogs.id, blogs.blogtitle, blogs.blogcontent,blogs.wordcount, blogtypes.typename, blogs.create_at, blogs.update_at, blogs.descr ORDER BY create_at DESC"
  135. blog_list = fetch_all(select_query, params=params, fetchall=True)
  136. return response_success(data=blog_list, message="blog serach succuessfully!")
  137. # 根据id查询博客
  138. @router.get("/search/{id}")
  139. @limiter.limit("5/minute")
  140. async def get_id_blog(request:Request,id: str = Path(description="博客id")):
  141. select_query = """SELECT blogs.id, blogtitle, blogcontent,wordcount, blogs.typeid, blogs.descr,JSON_ARRAYAGG(labels.id) AS labelnames,imglink FROM blogs
  142. LEFT JOIN `blogtypes` ON blogs.typeid = blogtypes.id
  143. LEFT JOIN blog_label ON blogs.id = blog_label.blogid
  144. LEFT JOIN labels ON blog_label.labelid = labels.id
  145. WHERE blogs.id = %s
  146. GROUP BY blogs.id;
  147. """
  148. blog_list = execute_query(select_query, (id,))
  149. if blog_list and isinstance(blog_list, dict):
  150. if 'labelnames' in blog_list and isinstance(blog_list['labelnames'], str):
  151. try:
  152. blog_list['labelnames'] = json.loads(blog_list['labelnames'])
  153. except json.JSONDecodeError:
  154. blog_list['labelnames'] = []
  155. return response_success(data=blog_list, message="blog search success")