AlgorithmShopManageController.py 16 KB

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