news.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. from fastapi import APIRouter, Form, Depends, HTTPException, File, UploadFile
  2. from typing import List,Optional,Union
  3. from fastapi.responses import FileResponse
  4. from random import randint
  5. from fastapi.security import OAuth2PasswordRequestForm
  6. from app.models.models import User,Favorite_course,News,Article_list
  7. from app.api import deps
  8. from sqlalchemy.orm import Session
  9. from typing import Any, Dict
  10. import secrets
  11. from fastapi_login.exceptions import InvalidCredentialsException
  12. from fastapi_login import LoginManager
  13. from datetime import timedelta,datetime
  14. from jose import jwt
  15. from emails.template import JinjaTemplate
  16. from tortoise.queryset import Q
  17. from fastapi.responses import HTMLResponse
  18. news = APIRouter()
  19. IMAGEDIR = "/var/www/ntcri/assets/news_files/"
  20. IMAGEDIR_short = "assets/news_files/"
  21. @news.get("/get_news")
  22. async def search_news(
  23. news_id : int = None,
  24. category :Optional[str] = None,
  25. page_num : Optional[int] = None,
  26. page_amount : Optional[int] = None
  27. ):
  28. try:
  29. news_list = News.all()
  30. if news_id :
  31. news_list = news_list.filter(id=news_id).all()
  32. if category:
  33. news_list = news_list.filter(category=category).all()
  34. count = await news_list.all().count()
  35. if page_num and page_amount:
  36. news_list = news_list.offset((page_num-1)*page_amount).limit(page_amount)
  37. news_list = await news_list.all().order_by("-create_time")
  38. news_objs = []
  39. for news_obj in news_list:
  40. try:
  41. news_tmp = {
  42. "news_id": news_obj.id,
  43. "title": news_obj.title,
  44. "category": news_obj.category,
  45. "create_time" : news_obj.create_time,
  46. "click_time" : news_obj.click_time,
  47. "content" : news_obj.content,
  48. "files" : news_obj.files,
  49. "URL" : news_obj.URL,
  50. "tags" : news_obj.tags,
  51. "cover_img": news_obj.cover_img
  52. }
  53. except:
  54. news_tmp = {"msg":"data wrong"}
  55. news_objs.append(news_tmp)
  56. return {"msg": "success", "code": 200, "total_num" : count,"news": news_objs}
  57. except Exception as e:
  58. return {"msg": str(e), "code": 500}
  59. async def create_upload_files(files:Optional[List[UploadFile]] = File(None)):
  60. files_url = {}
  61. if files :
  62. file_num = 1
  63. print(file_num)
  64. for file in files:
  65. contents = await file.read()
  66. #save the file
  67. with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
  68. f.write(contents)
  69. file_name = "file" + str(file_num)
  70. print(file_name)
  71. files_url[file_name]=f"{IMAGEDIR_short}{file.filename}"
  72. file_num=file_num+1
  73. return files_url
  74. @news.post("/insert_news_imgs")
  75. async def insert_imgs(
  76. files_url = Depends(create_upload_files)
  77. ):
  78. try:
  79. files = str(files_url),
  80. return {"msg": "success", "code": 200, "url": files}
  81. except Exception as e:
  82. return {"msg": str(e), "code": 500}
  83. @news.post("/insert_news")
  84. async def insert_news(
  85. title : str = Form(default=''),
  86. category : str = Form(default=''),
  87. content : str = Form(default=''),
  88. URL :str = Form(default=''),
  89. tags : str = Form(default='[]'),
  90. files_url = Depends(create_upload_files),
  91. create_time :str = Form(default=datetime.now()),
  92. cover_img_file:UploadFile = File(default='')
  93. ):
  94. try:
  95. cover_img = ''
  96. if cover_img_file != '':
  97. contents = await cover_img_file.read()
  98. #save the file
  99. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  100. f.write(contents)
  101. cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  102. new_news = await News.create(
  103. title=title,
  104. category=category,
  105. content=content,
  106. create_time = create_time,
  107. files = str(files_url),
  108. URL = URL,
  109. tags = tags,
  110. cover_img = cover_img
  111. )
  112. return {"msg": "success", "code": 200, "new_news": new_news.id}
  113. except Exception as e:
  114. return {"msg": str(e), "code": 500}
  115. @news.post("/update_news")
  116. async def update_news(
  117. news_id : int = Form(default=0),
  118. title : str = Form(default=''),
  119. category : str = Form(default=''),
  120. create_time :str = Form(default=datetime.now()),
  121. content : str = Form(default=''),
  122. URL :str = Form(default=''),
  123. tags : str = Form(default='[]'),
  124. files_url = Depends(create_upload_files),
  125. cover_img_file:UploadFile = File(default=''),
  126. ):
  127. try:
  128. if news_id == 0 :
  129. return {"msg": "no ID"}
  130. news_obj = await News.get(id=news_id)
  131. if title.strip() != '':
  132. news_obj.title = title
  133. if category.strip() != '':
  134. news_obj.category = category
  135. if create_time != '':
  136. news_obj.create_time = create_time
  137. if content.strip() != '':
  138. news_obj.content = content
  139. if URL.strip() != '':
  140. news_obj.URL = URL
  141. if tags != '[]':
  142. news_obj.tags = tags
  143. if cover_img_file != '':
  144. contents = await cover_img_file.read()
  145. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  146. f.write(contents)
  147. news_obj.cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  148. news_obj.files = str(files_url)
  149. await news_obj.save()
  150. return {"msg": "success", "code": 200}
  151. except Exception as e:
  152. return {"msg": str(e), "code": 500}
  153. @news.post("/delete_news")
  154. async def delete_news(id: int = 0):
  155. if id != 0:
  156. await News.filter(id=id).delete()
  157. return {"msg": "success", "code": 200}
  158. else :
  159. return {"msg": "please input ID", "code": 200}
  160. @news.get("/search_news_like")
  161. async def search_class_like(keyword: str):
  162. try:
  163. news_list = await News.filter(
  164. Q(title__icontains=keyword)|
  165. Q(category__icontains=keyword)|
  166. Q(content__icontains=keyword)|
  167. Q(tags__icontains=keyword)
  168. ).all()
  169. news_objs = []
  170. for news_obj in news_list:
  171. news_tmp = {
  172. "news_id": news_obj.id,
  173. "title": news_obj.title,
  174. "category": news_obj.category,
  175. "create_time" : news_obj.create_time,
  176. "click_time" : news_obj.click_time,
  177. "content" : news_obj.content,
  178. "files" : news_obj.files,
  179. "URL" : news_obj.URL,
  180. "tags" : news_obj.tags,
  181. "cover_img": news_obj.cover_img
  182. }
  183. news_objs.append(news_tmp)
  184. return {"msg": "success", "code": 200, "news": news_objs}
  185. except Exception as e:
  186. return {"msg": str(e), "code": 500}