article.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. for dic,obj in article_obj:
  70. article_tmp[dic]=obj
  71. #print(dic,obj)
  72. article_tmp["article_id"]= article_obj.id
  73. except Exception as e:
  74. article_tmp = {"msg":str(e)}
  75. article_objs.append(article_tmp)
  76. return {"msg": "success", "code": 200, "total_num":count,"articles": article_objs}
  77. except Exception as e:
  78. return {"msg": str(e), "code": 500}
  79. @article.post("/insert_article_imgs")
  80. async def insert_imgs(
  81. files_url = Depends(create_upload_files)
  82. ):
  83. try:
  84. files = str(files_url),
  85. return {"msg": "success", "code": 200, "url": files}
  86. except Exception as e:
  87. return {"msg": str(e), "code": 500}
  88. @article.post("/insert_article")
  89. async def insert_article(
  90. title : str = Form(default=''),
  91. school_id : int = Form(default=1),
  92. group_id : int = Form(default=1),
  93. group_sort : str = Form(default=''),
  94. tags : str = Form(default='[]'),
  95. category : str = Form(default=''),
  96. content : str = Form(default=''),
  97. depiction :str = Form(default=''),
  98. vedio_url :str = Form(default=''),
  99. cover_img_file:UploadFile = File(default=''),
  100. url : str = Form(default=''),
  101. recommend: int = Form(default=0),
  102. writer:str = Form(default=None),
  103. publish:str = Form(default=None),
  104. publish_date:datetime = Form(default=None),
  105. language:str = Form(default=None),
  106. buy_way:str = Form(default=None),
  107. files = Depends(create_upload_files)
  108. ):
  109. try:
  110. cover_img = ''
  111. if cover_img_file != '':
  112. contents = await cover_img_file.read()
  113. #save the file
  114. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  115. f.write(contents)
  116. cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  117. new_article = await Article_list.create(
  118. title = title,
  119. school_id = school_id,
  120. group_id = group_id,
  121. group_sort = group_sort,
  122. create_user_id = 0,
  123. create_time = datetime.now(),
  124. latest_update_user_id = 0,
  125. latest_update_time = datetime.now(),
  126. tags = tags,
  127. category = category,
  128. content = content,
  129. depiction = depiction,
  130. vedio_url =vedio_url,
  131. cover_img = cover_img,
  132. click_time = 0,
  133. is_del = 0,
  134. url = url ,
  135. files = files,
  136. recommend = recommend,
  137. writer = writer,
  138. publish = publish,
  139. publish_date = publish_date,
  140. language = language,
  141. buy_way = buy_way
  142. )
  143. return {"msg": "success", "code": 200, "new_article": new_article.id}
  144. except Exception as e:
  145. return {"msg": str(e), "code": 500}
  146. @article.post("/update_article")
  147. async def update_article(
  148. article_id : int = Form(default=0),
  149. title : str = Form(default=''),
  150. school_id : int = Form(default=0),
  151. group_id : int = Form(default=0),
  152. group_sort : str = Form(default=''),
  153. tags : str = Form(default='[]'),
  154. category : str = Form(default=''),
  155. content : str = Form(default=''),
  156. depiction :str = Form(default=''),
  157. vedio_url :str = Form(default=''),
  158. url :str = Form(default=''),
  159. cover_img_file:UploadFile = File(default=''),
  160. recommend: int = Form(default=0),
  161. writer:str = Form(default=None),
  162. publish:str = Form(default=None),
  163. publish_date:datetime = Form(default=None),
  164. language:str = Form(default=None),
  165. buy_way:str = Form(default=None),
  166. files :str = Form(default=None)
  167. ):
  168. try:
  169. if article_id == 0 :
  170. return {"msg": "no ID"}
  171. article_obj = await Article_list.get(id=article_id)
  172. if title.strip() != '':
  173. article_obj.title = title
  174. if school_id != 0:
  175. article_obj.school_id = school_id
  176. if group_id != 0:
  177. article_obj.group_id = group_id
  178. if group_sort.strip() != '':
  179. article_obj.group_sort = group_sort
  180. print(group_sort +"change")
  181. if category.strip() != '':
  182. article_obj.category = category
  183. if content.strip() != '':
  184. article_obj.content = content
  185. if depiction.strip() != '':
  186. article_obj.depiction = depiction
  187. if vedio_url.strip() != '':
  188. article_obj.vedio_url = vedio_url
  189. if tags != '[]':
  190. article_obj.tags = tags
  191. if url != '':
  192. article_obj.url = url
  193. if recommend != None:
  194. article_obj.recommend = recommend
  195. if files :
  196. article_obj.files = files
  197. if cover_img_file != '':
  198. contents = await cover_img_file.read()
  199. with open(f"{IMAGEDIR}{cover_img_file.filename}", "wb") as f:
  200. f.write(contents)
  201. article_obj.cover_img = f"{IMAGEDIR_short}{cover_img_file.filename}"
  202. if writer:
  203. article_obj.writer = writer
  204. if publish:
  205. article_obj.publish = publish
  206. if publish_date:
  207. article_obj.publish_date = publish_date
  208. if language:
  209. article_obj.language = language
  210. if buy_way:
  211. article_obj.buy_way = buy_way
  212. await article_obj.save()
  213. return {"msg": "success", "code": 200}
  214. except Exception as e:
  215. return {"msg": str(e), "code": 500}
  216. @article.post("/delete_article")
  217. async def delete_article(id: int = 0):
  218. if id != 0:
  219. article_obj = await Article_list.get(id=id)
  220. article_obj.is_del = 1
  221. await article_obj.save()
  222. return {"msg": "success", "code": 200}
  223. else :
  224. return {"msg": "please input ID", "code": 200}
  225. @article.get("/search_article_like")
  226. async def search_article_like(keyword: str,page_num : Optional[int] = None,
  227. page_amount : Optional[int] = None):
  228. try:
  229. article_list = Article_list.filter(
  230. Q(title__icontains=keyword)|
  231. Q(category__icontains=keyword)|
  232. Q(content__icontains=keyword)|
  233. Q(depiction__icontains=keyword)|
  234. Q(tags__icontains=keyword)
  235. ).all()
  236. count = await article_list.all().count()
  237. if page_num and page_amount:
  238. article_list = article_list.offset((page_num-1)*page_amount).limit(page_amount)
  239. article_list = await article_list.all().order_by("-create_time")
  240. article_objs = []
  241. for article_obj in article_list:
  242. try:
  243. article_tmp = {
  244. "article_id": article_obj.id,
  245. "title": article_obj.title,
  246. "school_id" :article_obj.school_id,
  247. "group_sort" :article_obj.group_sort,
  248. "group_id" :article_obj.group_id,
  249. "category": article_obj.category,
  250. "create_time" : article_obj.create_time,
  251. "click_time" : article_obj.click_time,
  252. "depiction" : article_obj.depiction,
  253. "content" : article_obj.content,
  254. "files" : article_obj.files,
  255. "video_url" : article_obj.vedio_url,
  256. "tags" : article_obj.tags,
  257. "cover_img": article_obj.cover_img,
  258. "url" : article_obj.url
  259. }
  260. except:
  261. article_tmp = {"msg":"data wrong"}
  262. article_objs.append(article_tmp)
  263. return {"msg": "success", "code": 200, "total_num":count,"article": article_objs}
  264. except Exception as e:
  265. return {"msg": str(e), "code": 500}
  266. @article.get("/add_click_time")
  267. async def add_click_time(article_id: int ):
  268. try:
  269. article_ = await Article_list.get_or_none(id=article_id)
  270. if article_ == None:
  271. return {"msg": "no this article id", "code": 500}
  272. if article_.click_time == None:
  273. article_.click_time = 1
  274. else:
  275. article_.click_time = article_.click_time +1
  276. await article_.save()
  277. return {"msg": "success", "code": 200}
  278. except Exception as e:
  279. return {"msg": str(e), "code": 500}