article.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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,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. article = APIRouter()
  19. IMAGEDIR = "/var/www/ntcri/assets/article_files/"
  20. IMAGEDIR_short = "assets/article_files/"
  21. async def create_upload_files(files:Optional[List[UploadFile]] = File(None)):
  22. files_url = {}
  23. if files :
  24. file_num = 1
  25. print(file_num)
  26. for file in files:
  27. contents = await file.read()
  28. #save the file
  29. with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
  30. f.write(contents)
  31. file_name = "file" + str(file_num)
  32. print(file_name)
  33. files_url[file_name]=f"{IMAGEDIR_short}{file.filename}"
  34. file_num=file_num+1
  35. return files_url
  36. @article.get("/get_article")
  37. async def get_article(
  38. article_id : Optional[int] = None,
  39. group_id : Optional[int] = None,
  40. group_sort : Optional[str] = None,
  41. category : Optional[str] = None,
  42. tags : Optional[str] = None,
  43. recommend: Optional[int] = None,
  44. page_num : Optional[int] = None,
  45. page_amount : Optional[int] = None
  46. ):
  47. try:
  48. article_list = Article_list.filter(is_del = 0).all()
  49. if group_sort:
  50. article_list = article_list.filter(group_sort = group_sort).all()
  51. if category:
  52. article_list = article_list.filter(Q(category__icontains=category)).all()
  53. if tags:
  54. article_list = article_list.filter(Q(tags__icontains=category)).all()
  55. if recommend:
  56. article_list = article_list.filter(Q(recommend=recommend)).all()
  57. if article_id :
  58. article_list = article_list.filter(id = article_id).all()
  59. if group_id :
  60. article_list = article_list.filter(group_id = group_id).all()
  61. count = await article_list.all().count()
  62. if page_num and page_amount:
  63. article_list = article_list.offset((page_num-1)*page_amount).limit(page_amount)
  64. article_list = await article_list.all().order_by("-create_time")
  65. article_objs = []
  66. for article_obj in article_list:
  67. try:
  68. article_tmp = {
  69. "article_id": article_obj.id,
  70. "title": article_obj.title,
  71. "school_id" :article_obj.school_id,
  72. "group_sort" :article_obj.group_sort,
  73. "group_id" :article_obj.group_id,
  74. "category": article_obj.category,
  75. "create_time" : article_obj.create_time,
  76. "click_time" : article_obj.click_time,
  77. "depiction" : article_obj.depiction,
  78. "content" : article_obj.content,
  79. "files" : article_obj.files,
  80. "video_url" : article_obj.vedio_url,
  81. "tags" : article_obj.tags,
  82. "cover_img": article_obj.cover_img,
  83. "recommend" :article_obj.recommend,
  84. "url" : article_obj.url
  85. }
  86. except:
  87. article_tmp = {"msg":"data wrong"}
  88. article_objs.append(article_tmp)
  89. return {"msg": "success", "code": 200, "total_num":count,"articles": article_objs}
  90. except Exception as e:
  91. return {"msg": str(e), "code": 500}
  92. @article.post("/insert_article_imgs")
  93. async def insert_imgs(
  94. files_url = Depends(create_upload_files)
  95. ):
  96. try:
  97. files = str(files_url),
  98. return {"msg": "success", "code": 200, "url": files}
  99. except Exception as e:
  100. return {"msg": str(e), "code": 500}
  101. @article.post("/insert_article")
  102. async def insert_article(
  103. title : str = Form(default=''),
  104. school_id : int = Form(default=1),
  105. group_id : int = Form(default=1),
  106. group_sort : str = Form(default=''),
  107. tags : str = Form(default='[]'),
  108. category : str = Form(default=''),
  109. content : str = Form(default=''),
  110. depiction :str = Form(default=''),
  111. vedio_url :str = Form(default=''),
  112. files : str = Form(default='{}'),
  113. cover_img_file:UploadFile = File(default=''),
  114. url : str = Form(default=''),
  115. recommend: int = Form(default=0)
  116. ):
  117. try:
  118. cover_img = ''
  119. if cover_img_file != '':
  120. contents = await cover_img_file.read()
  121. #save the file
  122. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  123. f.write(contents)
  124. cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  125. new_article = await Article_list.create(
  126. title = title,
  127. school_id = school_id,
  128. group_id = group_id,
  129. group_sort = group_sort,
  130. create_user_id = 0,
  131. create_time = datetime.now(),
  132. latest_update_user_id = 0,
  133. latest_update_time = datetime.now(),
  134. tags = tags,
  135. category = category,
  136. content = content,
  137. depiction = depiction,
  138. vedio_url =vedio_url,
  139. cover_img = cover_img,
  140. click_time = 0,
  141. is_del = 0,
  142. url = url ,
  143. files = files,
  144. recommend = recommend
  145. )
  146. return {"msg": "success", "code": 200, "new_article": new_article.id}
  147. except Exception as e:
  148. return {"msg": str(e), "code": 500}
  149. @article.post("/update_article")
  150. async def update_article(
  151. article_id : int = Form(default=0),
  152. title : str = Form(default=''),
  153. school_id : int = Form(default=0),
  154. group_id : int = Form(default=0),
  155. group_sort : str = Form(default=''),
  156. tags : str = Form(default='[]'),
  157. category : str = Form(default=''),
  158. content : str = Form(default=''),
  159. depiction :str = Form(default=''),
  160. vedio_url :str = Form(default=''),
  161. url :str = Form(default=''),
  162. cover_img_file:UploadFile = File(default=''),
  163. recommend: int = Form(default=0)
  164. ):
  165. try:
  166. if article_id == 0 :
  167. return {"msg": "no ID"}
  168. article_obj = await Article_list.get(id=article_id)
  169. if title.strip() != '':
  170. article_obj.title = title
  171. if school_id != 0:
  172. article_obj.school_id = school_id
  173. if group_id != 0:
  174. article_obj.group_id = group_id
  175. if group_sort.strip() != '':
  176. article_obj.group_sort = group_sort
  177. print(group_sort +"change")
  178. if category.strip() != '':
  179. article_obj.category = category
  180. if content.strip() != '':
  181. article_obj.content = content
  182. if depiction.strip() != '':
  183. article_obj.depiction = depiction
  184. if vedio_url.strip() != '':
  185. article_obj.vedio_url = vedio_url
  186. if tags != '[]':
  187. article_obj.tags = tags
  188. if url != '':
  189. article_obj.url = url
  190. if recommend:
  191. article_obj.recommend = recommend
  192. if cover_img_file != '':
  193. contents = await cover_img_file.read()
  194. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  195. f.write(contents)
  196. article_obj.cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  197. await article_obj.save()
  198. return {"msg": "success", "code": 200}
  199. except Exception as e:
  200. return {"msg": str(e), "code": 500}
  201. @article.post("/delete_article")
  202. async def delete_article(id: int = 0):
  203. if id != 0:
  204. article_obj = await Article_list.get(id=id)
  205. article_obj.is_del = 1
  206. await article_obj.save()
  207. return {"msg": "success", "code": 200}
  208. else :
  209. return {"msg": "please input ID", "code": 200}
  210. @article.get("/search_article_like")
  211. async def search_article_like(keyword: str,page_num : Optional[int] = None,
  212. page_amount : Optional[int] = None):
  213. try:
  214. article_list = Article_list.filter(
  215. Q(title__icontains=keyword)|
  216. Q(category__icontains=keyword)|
  217. Q(content__icontains=keyword)|
  218. Q(depiction__icontains=keyword)|
  219. Q(tags__icontains=keyword)
  220. ).all()
  221. count = await article_list.all().count()
  222. if page_num and page_amount:
  223. article_list = article_list.offset((page_num-1)*page_amount).limit(page_amount)
  224. article_list = await article_list.all().order_by("-create_time")
  225. article_objs = []
  226. for article_obj in article_list:
  227. try:
  228. article_tmp = {
  229. "article_id": article_obj.id,
  230. "title": article_obj.title,
  231. "school_id" :article_obj.school_id,
  232. "group_sort" :article_obj.group_sort,
  233. "group_id" :article_obj.group_id,
  234. "category": article_obj.category,
  235. "create_time" : article_obj.create_time,
  236. "click_time" : article_obj.click_time,
  237. "depiction" : article_obj.depiction,
  238. "content" : article_obj.content,
  239. "files" : article_obj.files,
  240. "video_url" : article_obj.vedio_url,
  241. "tags" : article_obj.tags,
  242. "cover_img": article_obj.cover_img,
  243. "url" : article_obj.url
  244. }
  245. except:
  246. article_tmp = {"msg":"data wrong"}
  247. article_objs.append(article_tmp)
  248. return {"msg": "success", "code": 200, "total_num":count,"article": article_objs}
  249. except Exception as e:
  250. return {"msg": str(e), "code": 500}