AlgorithmShopManageController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : AlgorithmShopManageController.py
  4. @Time : 2023/7/25 9:48
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import json
  10. import time
  11. from decimal import Decimal
  12. from django.core.paginator import Paginator
  13. from django.views import View
  14. from Model.models import DeviceAlgorithmExplain, DeviceAlgorithmType
  15. from Object.AWS.AmazonS3Util import AmazonS3Util
  16. from Object.ResponseObject import ResponseObject
  17. from Object.TokenObject import TokenObject
  18. from Ansjer.config import CONFIG_INFO, CONFIG_EUR, CONFIG_US, CONFIG_TEST, CONFIG_CN, AWS_ACCESS_KEY_ID, \
  19. AWS_SECRET_ACCESS_KEY, AWS_SES_ACCESS_REGION
  20. class AlgorithmShopManageView(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. operation = kwargs.get('operation')
  24. api_version = kwargs.get('apiVersion')
  25. return self.validation(request.GET, request, operation, api_version)
  26. def post(self, request, *args, **kwargs):
  27. request.encoding = 'utf-8'
  28. operation = kwargs.get('operation')
  29. api_version = kwargs.get('apiVersion')
  30. return self.validation(request.POST, request, operation, api_version)
  31. def validation(self, request_dict, request, operation, api_version='v1'):
  32. token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  33. response = ResponseObject()
  34. if token.code != 0:
  35. return response.json(token.code)
  36. ''' 后台管理'''
  37. response = ResponseObject(returntype='pc')
  38. if operation == 'update':
  39. return self.algorithm_update(request_dict, response, api_version)
  40. elif operation == 'query':
  41. return self.algorithm_query(request_dict, response)
  42. elif operation == 'save':
  43. return self.algorithm_save(request, request_dict, response)
  44. elif operation == 'delete':
  45. return self.algorithm_delete(request_dict, response)
  46. elif operation == 'edit':
  47. return self.algorithm_edit(request, request_dict, response)
  48. else:
  49. return response.json(404)
  50. @classmethod
  51. def algorithm_update(cls, request_dict, response, api_version):
  52. try:
  53. a_id = request_dict.get('aId', None)
  54. lang = request_dict.get('lang', None)
  55. title = request_dict.get('title', None)
  56. subtitle = request_dict.get('subtitle', None)
  57. introduction = request_dict.get('introduction', None)
  58. install_explain = request_dict.get('installExplain', None)
  59. concerning = request_dict.get('concerning', None)
  60. risk_warning = request_dict.get('riskWarning', None)
  61. if not all([a_id, lang]):
  62. return response.json()
  63. a_explain_qs = DeviceAlgorithmExplain.objects.filter(algorithm_type_id=int(a_id), lang=lang)
  64. if not a_explain_qs.exists():
  65. return response.json(173)
  66. data = {}
  67. if title:
  68. data['title'] = title
  69. if subtitle:
  70. data['subtitle'] = subtitle
  71. if introduction:
  72. data['introduction'] = introduction
  73. if install_explain:
  74. data['install_explain'] = install_explain
  75. if concerning:
  76. data['concerning'] = concerning
  77. if risk_warning:
  78. data['risk_warning'] = risk_warning
  79. a_explain_qs.update(**data)
  80. return response.json(0)
  81. except Exception as e:
  82. print(repr(e))
  83. return response.json(500)
  84. @classmethod
  85. def algorithm_query(cls, request_dict, response):
  86. algorithm_type = request_dict.get('algorithmType', None)
  87. tag = request_dict.get('tag', None)
  88. status = request_dict.get('status', None)
  89. page = request_dict.get('page', 1)
  90. page_size = request_dict.get('pageSize', 10)
  91. try:
  92. device_algorithm_type_qs = DeviceAlgorithmType.objects.all()
  93. if algorithm_type:
  94. device_algorithm_type_qs = device_algorithm_type_qs.filter(type=algorithm_type)
  95. if tag:
  96. device_algorithm_type_qs = device_algorithm_type_qs.filter(tag=tag)
  97. if status:
  98. device_algorithm_type_qs = device_algorithm_type_qs.filter(status=status)
  99. # 分页
  100. paginator = Paginator(device_algorithm_type_qs.order_by("-sort"), page_size) # 每页显示 page_size 条
  101. device_algorithm_type_page = paginator.get_page(page) # 获取当前页的数据
  102. device_algorithm_type_list = []
  103. for device_algorithm_type in device_algorithm_type_page:
  104. device_algorithm_explain_qs = DeviceAlgorithmExplain.objects.filter(
  105. algorithm_type_id=device_algorithm_type.id)
  106. device_algorithm_explain_list = []
  107. for device_algorithm_explain in device_algorithm_explain_qs:
  108. device_algorithm_explain_list.append(
  109. {
  110. 'algorithmExplainId': device_algorithm_explain.id,
  111. 'lang': device_algorithm_explain.lang,
  112. 'title': device_algorithm_explain.title,
  113. 'subtitle': device_algorithm_explain.subtitle,
  114. 'price': device_algorithm_explain.price,
  115. 'introduction': device_algorithm_explain.introduction,
  116. 'installExplain': device_algorithm_explain.install_explain,
  117. 'concerning': device_algorithm_explain.concerning,
  118. 'riskWarning': device_algorithm_explain.risk_warning,
  119. }
  120. )
  121. device_algorithm_explain_qs = DeviceAlgorithmExplain.objects.filter(
  122. algorithm_type_id=device_algorithm_type.id)
  123. translation_num = device_algorithm_explain_qs.count()
  124. device_algorithm_explain = device_algorithm_explain_qs.filter(lang='cn').values("title")
  125. if device_algorithm_explain.exists():
  126. title = device_algorithm_explain[0]["title"]
  127. else:
  128. device_algorithm_explain = device_algorithm_explain_qs.values("title")
  129. if device_algorithm_explain.exists():
  130. title = device_algorithm_explain[0]["title"]
  131. else:
  132. title = ""
  133. device_algorithm_type_list.append({
  134. "algorithmId": device_algorithm_type.id,
  135. "title": title,
  136. "algorithmType": device_algorithm_type.type,
  137. "memory": device_algorithm_type.memory,
  138. "downCount": device_algorithm_type.down_count,
  139. "tag": device_algorithm_type.tag,
  140. "status": device_algorithm_type.status,
  141. "expireTime": device_algorithm_type.expire_time if device_algorithm_type.status == 1 else 0,
  142. "sort": device_algorithm_type.sort,
  143. "basicFunction": device_algorithm_type.basic_function,
  144. "imageUrl": device_algorithm_type.image_url,
  145. "detailsImgUrl": device_algorithm_type.details_img_url,
  146. "iconUrl": device_algorithm_type.icon_url,
  147. "resource": device_algorithm_type.resource,
  148. "deviceAlgorithmExplain": device_algorithm_explain_list,
  149. "translationNum": translation_num
  150. })
  151. data = {
  152. 'list': device_algorithm_type_list,
  153. 'total': paginator.count,
  154. }
  155. return response.json(0, data)
  156. except Exception as e:
  157. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  158. @classmethod
  159. def algorithm_save(cls, request, request_dict, response):
  160. algorithm_type = request_dict.get('algorithmType', None)
  161. memory = request_dict.get('memory', "")
  162. tag = request_dict.get('tag', 0)
  163. status = request_dict.get('status', 0)
  164. expire_time = request_dict.get('expireTime', 0)
  165. sort = request_dict.get('sort', 0)
  166. basic_function = request_dict.get('basicFunction', '')
  167. resource = request_dict.get('resource', None)
  168. lang_configs = request_dict.get('langExplainConfig', None)
  169. image_file = request.FILES.get('imageFile', None)
  170. details_img_file = request.FILES.get('detailsImgFile', None)
  171. icon_file = request.FILES.get('iconFile', None)
  172. if not algorithm_type:
  173. return response.json(444)
  174. try:
  175. if lang_configs:
  176. lang_configs = json.loads(lang_configs)
  177. else:
  178. lang_configs = []
  179. device_algorithm_type_qs = DeviceAlgorithmType.objects.filter(type=algorithm_type)
  180. if device_algorithm_type_qs.exists():
  181. return response.json(174)
  182. # 上传图片至存储桶
  183. icon_url = cls.upload_image("app/algorithm-shop/icon/", algorithm_type, icon_file)
  184. image_url = cls.upload_image("app/algorithm-shop/image/", algorithm_type, image_file)
  185. details_img_url = cls.upload_image("app/algorithm-shop/details-img/", algorithm_type, details_img_file)
  186. # 激活时间
  187. expire_time = expire_time if status == 1 else 0
  188. # 创建算法类型
  189. device_algorithm_type = DeviceAlgorithmType.objects.create(type=algorithm_type, memory=memory, tag=tag,
  190. status=status, expire_time=expire_time,
  191. sort=sort,
  192. basic_function=basic_function,
  193. image_url=image_url,
  194. details_img_url=details_img_url,
  195. icon_url=icon_url,
  196. resource=resource, created_time=int(time.time()))
  197. # 处理算法翻译数据
  198. explain_instances = []
  199. for lang_config in lang_configs:
  200. explain_instance = DeviceAlgorithmExplain(
  201. algorithm_type_id=int(device_algorithm_type.id), # 关联的 DeviceAlgorithmType 的 id
  202. title=lang_config['title'],
  203. subtitle=lang_config['subtitle'],
  204. price=Decimal(lang_config['price'] if lang_config['price'] else 0),
  205. introduction=lang_config['introduction'],
  206. install_explain=lang_config['installExplain'],
  207. concerning=lang_config['concerning'],
  208. risk_warning=lang_config['riskWarning'],
  209. lang=lang_config['lang'],
  210. updated_time=int(time.time()),
  211. created_time=int(time.time())
  212. )
  213. explain_instances.append(explain_instance)
  214. DeviceAlgorithmExplain.objects.bulk_create(explain_instances)
  215. return response.json(0)
  216. except Exception as e:
  217. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  218. @classmethod
  219. def algorithm_delete(cls, request_dict, response):
  220. algorithm_id = request_dict.get('algorithmId', None)
  221. if not algorithm_id:
  222. return response.json(444)
  223. DeviceAlgorithmExplain.objects.filter(algorithm_type_id=algorithm_id).delete()
  224. DeviceAlgorithmType.objects.filter(id=algorithm_id).delete()
  225. return response.json(0)
  226. @classmethod
  227. def upload_image(cls, directory, algorithm_type, image_file):
  228. if not image_file:
  229. return ""
  230. bucket = 'ansjerfilemanager'
  231. file_key = directory + f"{CONFIG_INFO}_{algorithm_type}.png"
  232. if CONFIG_INFO == CONFIG_TEST or CONFIG_INFO == CONFIG_CN or CONFIG_INFO == 'local':
  233. prefix_url = "https://ansjerfilemanager.s3.cn-northwest-1.amazonaws.com.cn/"
  234. s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[0], AWS_SECRET_ACCESS_KEY[0], 'cn-northwest-1')
  235. else:
  236. prefix_url = "https://ansjerfilemanager.s3.amazonaws.com/"
  237. s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], AWS_SES_ACCESS_REGION)
  238. s3.upload_file_obj(
  239. bucket,
  240. file_key,
  241. image_file,
  242. {'ContentType': image_file.content_type, 'ACL': 'public-read'})
  243. return prefix_url + file_key
  244. @classmethod
  245. def algorithm_edit(cls, request, request_dict, response):
  246. algorithm_id = request_dict.get('algorithmId', None)
  247. memory = request_dict.get('memory', '')
  248. tag = request_dict.get('tag', 0)
  249. status = request_dict.get('status', 0)
  250. expire_time = request_dict.get('expireTime', 0)
  251. sort = request_dict.get('sort', 0)
  252. basic_function = request_dict.get('basicFunctions', '')
  253. resource = request_dict.get('resource', None)
  254. lang_configs = request_dict.get('langExplainConfig', None)
  255. image_file = request.FILES.get('imageFile', None)
  256. details_img_file = request.FILES.get('detailsImgFile', None)
  257. icon_file = request.FILES.get('iconFile', None)
  258. if not algorithm_id:
  259. return response.json(444)
  260. try:
  261. device_algorithm_type = DeviceAlgorithmType.objects.get(pk=algorithm_id)
  262. if not device_algorithm_type:
  263. return response.json(173)
  264. algorithm_type = device_algorithm_type.type
  265. if lang_configs:
  266. lang_configs = json.loads(lang_configs)
  267. DeviceAlgorithmExplain.objects.filter(algorithm_type_id=algorithm_id).delete()
  268. # 处理算法翻译数据
  269. explain_instances = []
  270. for lang_config in lang_configs:
  271. explain_instance = DeviceAlgorithmExplain(
  272. algorithm_type_id=int(algorithm_id), # 关联的 DeviceAlgorithmType 的 id
  273. title=lang_config['title'],
  274. subtitle=lang_config['subtitle'],
  275. price=Decimal(lang_config['price'] if lang_config['price'] else 0),
  276. introduction=lang_config['introduction'],
  277. install_explain=lang_config['installExplain'],
  278. concerning=lang_config['concerning'],
  279. risk_warning=lang_config['riskWarning'],
  280. lang=lang_config['lang'],
  281. updated_time=int(time.time()),
  282. created_time=int(time.time())
  283. )
  284. explain_instances.append(explain_instance)
  285. DeviceAlgorithmExplain.objects.bulk_create(explain_instances)
  286. if memory:
  287. device_algorithm_type.memory = memory
  288. if tag:
  289. device_algorithm_type.tag = tag
  290. if status:
  291. device_algorithm_type.status = status
  292. if status == 1 and expire_time:
  293. device_algorithm_type.expire_time = expire_time
  294. if sort:
  295. device_algorithm_type.sort = sort
  296. if basic_function:
  297. device_algorithm_type.basic_function = basic_function
  298. if resource:
  299. device_algorithm_type.resource = resource
  300. if image_file:
  301. image_url = cls.upload_image("app/algorithm-shop/image/", algorithm_type, image_file)
  302. device_algorithm_type.image_url = image_url
  303. if icon_file:
  304. icon_url = cls.upload_image("app/algorithm-shop/icon/", algorithm_type, icon_file)
  305. device_algorithm_type.icon_url = icon_url
  306. if details_img_file:
  307. details_img_url = cls.upload_image("app/algorithm-shop/details-img/", algorithm_type, details_img_file)
  308. device_algorithm_type.details_img_url = details_img_url
  309. device_algorithm_type.save()
  310. return response.json(0)
  311. except Exception as e:
  312. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))