DeviceDataController.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UserDataController.py
  4. @Time : 2022/8/16 10:44
  5. @Author : peng
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import datetime
  10. import requests
  11. from django.db.models import Sum
  12. from django.views.generic.base import View
  13. from Model.models import DeviceInfoSummary
  14. from Service.CommonService import CommonService
  15. # 设备数据
  16. class DeviceDataView(View):
  17. def get(self, request, *args, **kwargs):
  18. request.encoding = 'utf-8'
  19. operation = kwargs.get('operation')
  20. return self.validation(request.GET, request, operation)
  21. def post(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. operation = kwargs.get('operation')
  24. return self.validation(request.POST, request, operation)
  25. def validation(self, request_dict, request, operation):
  26. token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
  27. if token_code != 0:
  28. return response.json(token_code)
  29. if operation == 'type': # 统计设备类型
  30. return self.type_statistics(response)
  31. if operation == 'regional': # 设备地区分布
  32. return self.regional_statistics(response)
  33. if operation == 'addDevice': # 查询设备增长数据(数据有些许差异)
  34. return self.add_device(request_dict, response)
  35. if operation == 'active': # 设备活跃数据
  36. return self.device_active(request_dict, response)
  37. if operation == 'global/regional': # 全球设备分布
  38. return self.global_regional(request, request_dict, response)
  39. if operation == 'global/type': # 全球设备类型
  40. return self.golbal_type(request, request_dict, response)
  41. if operation == 'global/active': # 全球设备活跃分布
  42. return self.golbal_active(request, request_dict, response)
  43. if operation == 'global/addDevice': # 全球新增设备数据
  44. return self.golbal_add_device(request, request_dict, response)
  45. else:
  46. return response.json(414)
  47. @classmethod
  48. def golbal_add_device(cls, request, request_dict, response):
  49. """
  50. 全球新增设备数据
  51. @param request:请求
  52. @param request_dict:请求参数
  53. @param response: 响应对象
  54. """
  55. url_list = CommonService.get_domain_name()
  56. try:
  57. headers = {
  58. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  59. }
  60. device_list = []
  61. device_count = 0
  62. type_list = []
  63. type_count = 0
  64. region_list = []
  65. region_count = 0
  66. order_list = []
  67. order_count = 0
  68. for url in url_list:
  69. url = url + request.path.replace('global/', '')
  70. res = requests.get(url=url, params=request_dict, headers=headers)
  71. result = res.json()
  72. if result['result_code'] == 0:
  73. for item in result['result']['addDevice']:
  74. flag = 0
  75. for each in device_list:
  76. if item['startTime'] == each['startTime'] and item['endTime'] == each['endTime']:
  77. each['count'] += item['count']
  78. device_count += item['count']
  79. flag = 1
  80. break
  81. if flag == 0:
  82. device_list.append(item)
  83. device_count += item['count']
  84. for item in result['result']['region']:
  85. flag = 0
  86. for each in region_list:
  87. if item['countryName'] == each['countryName']:
  88. each['count'] += item['count']
  89. region_count += item['count']
  90. flag = 1
  91. break
  92. if flag == 0:
  93. region_list.append(item)
  94. region_count += item['count']
  95. for item in result['result']['type']:
  96. flag = 0
  97. for each in type_list:
  98. if item['type'] == each['type']:
  99. each['count'] += item['count']
  100. type_count += item['count']
  101. flag = 1
  102. break
  103. if flag == 0:
  104. type_list.append(item)
  105. type_count += item['count']
  106. for item in result['result']['version']:
  107. flag = 0
  108. for each in order_list:
  109. if item['type'] == each['type']:
  110. each['count'] += item['count']
  111. order_count += item['count']
  112. flag = 1
  113. break
  114. if flag == 0:
  115. order_list.append(item)
  116. order_count += item['count']
  117. if order_count != 0:
  118. item['rate'] = round(item['count'] / order_count * 100, 2)
  119. else:
  120. break
  121. else:
  122. return response.json(result['result_code'], result['result'])
  123. for item in device_list:
  124. item['rate'] = round(item['count'] / device_count * 100, 2) if device_count else 0
  125. for item in region_list:
  126. item['rate'] = round(item['count'] / region_count * 100, 2) if region_count else 0
  127. for item in type_list:
  128. item['rate'] = round(item['count'] / type_count * 100, 2) if type_count else 0
  129. for item in order_list:
  130. item['rate'] = round(item['count'] / order_count * 100, 2) if order_count else 0
  131. res = {
  132. 'device': device_list,
  133. 'type': CommonService.list_sort(type_list),
  134. 'region': CommonService.list_sort(region_list),
  135. 'version': CommonService.list_sort(order_list)
  136. }
  137. return response.json(0, res)
  138. except Exception as e:
  139. print(e)
  140. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  141. @classmethod
  142. def golbal_active(cls, request, request_dict, response):
  143. """
  144. 全球设备活跃分布
  145. @param request:请求
  146. @param request_dict:请求参数
  147. @param response: 响应对象
  148. """
  149. url_list = CommonService.get_domain_name()
  150. try:
  151. headers = {
  152. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  153. }
  154. type_list = []
  155. type_count = 0
  156. region_list = []
  157. region_count = 0
  158. for url in url_list:
  159. url = url + request.path.replace('global/', '')
  160. res = requests.get(url=url, params=request_dict, headers=headers)
  161. result = res.json()
  162. if result['result_code'] == 0:
  163. for item in result['result']['vodHls']:
  164. flag = 0
  165. for each in type_list:
  166. if item['startTime'] == each['startTime'] and item['endTime'] == each['endTime']:
  167. each['count'] += item['count']
  168. type_count += item['count']
  169. flag = 1
  170. break
  171. if flag == 0:
  172. type_list.append(item)
  173. type_count += item['count']
  174. for item in result['result']['region']:
  175. flag = 0
  176. for each in region_list:
  177. if item['countryName'] == each['countryName']:
  178. each['count'] += item['count']
  179. region_count += item['count']
  180. flag = 1
  181. break
  182. if flag == 0:
  183. region_list.append(item)
  184. region_count += item['count']
  185. else:
  186. return response.json(result['result_code'], result['result'])
  187. for item in region_list:
  188. item['rate'] = round(item['count'] / region_count * 100, 2) if region_count else 0
  189. for item in type_list:
  190. item['rate'] = round(item['count'] / type_count * 100, 2) if type_count else 0
  191. res = {
  192. 'device': type_list,
  193. 'region': CommonService.list_sort(region_list)
  194. }
  195. return response.json(0, res)
  196. except Exception as e:
  197. print(e)
  198. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  199. @classmethod
  200. def golbal_type(cls, request, request_dict, response):
  201. """
  202. 全球设备类型分布
  203. @param request:请求
  204. @param request_dict:请求参数
  205. @param response: 响应对象
  206. """
  207. url_list = CommonService.get_domain_name()
  208. try:
  209. headers = {
  210. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  211. }
  212. type_list = []
  213. type_count = 0
  214. for url in url_list:
  215. url = url + request.path.replace('global/', '')
  216. res = requests.get(url=url, params=request_dict, headers=headers)
  217. result = res.json()
  218. if result['result_code'] == 0:
  219. for item in result['result']['type']:
  220. flag = 0
  221. for each in type_list:
  222. if item['type'] == each['type']:
  223. each['count'] += item['count']
  224. type_count += item['count']
  225. flag = 1
  226. break
  227. if flag == 0:
  228. type_list.append(item)
  229. type_count += item['count']
  230. else:
  231. return response.json(result['result_code'], result['result'])
  232. for item in type_list:
  233. item['rate'] = round(item['count'] / type_count * 100, 2) if type_count else 0
  234. res = {
  235. 'type': CommonService.list_sort(type_list)
  236. }
  237. return response.json(0, res)
  238. except Exception as e:
  239. print(e)
  240. return response.json(500)
  241. @classmethod
  242. def global_regional(cls, request, request_dict, response):
  243. """
  244. 全球设备分布
  245. @param request:请求
  246. @param request_dict:请求参数
  247. @param response:响应对象
  248. @return:
  249. """
  250. url_list = CommonService.get_domain_name()
  251. try:
  252. headers = {
  253. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  254. }
  255. device_list = []
  256. device_count = 0
  257. region_list = []
  258. region_count = 0
  259. for url in url_list:
  260. url = url + request.path.replace('global/', '')
  261. res = requests.get(url=url, params=request_dict, headers=headers)
  262. result = res.json()
  263. if result['result_code'] == 0:
  264. # 处理地区
  265. for item in result['result']['countries']:
  266. flag = 0
  267. for each in device_list:
  268. if each['countryName'] == item['countryName']:
  269. each['count'] += int(item['count'])
  270. device_count += int(item['count'])
  271. flag = 1
  272. break
  273. if flag == 0:
  274. device_list.append(item)
  275. device_count += int(item['count'])
  276. for item in result['result']['continent']:
  277. flag = 0
  278. for each in region_list:
  279. if each['continentName'] == item['continentName']:
  280. each['count'] += item['count']
  281. region_count += item['count']
  282. flag = 1
  283. break
  284. if flag == 0:
  285. region_list.append(item)
  286. region_count += item['count']
  287. else:
  288. return response.json(result['result_code'], result['result'])
  289. for item in device_list:
  290. item['rate'] = round(item['count'] / device_count * 100, 2) if device_count else 0
  291. for item in region_list:
  292. item['rate'] = round(item['count'] / region_count * 100, 2) if region_count else 0
  293. res = {
  294. 'countries': CommonService.list_sort(device_list[:30]),
  295. 'continent': region_list
  296. }
  297. return response.json(0, res)
  298. except Exception as e:
  299. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  300. @classmethod
  301. def device_active(cls, request_dict, response):
  302. """
  303. 设备活跃数据
  304. @param request_dict:请求参数
  305. @request_dict starTime:开始时间
  306. @request_dict endTime:结束时间
  307. @param response:响应对象
  308. """
  309. start_time = request_dict.get('startTime', None) # 时间戳
  310. end_time = request_dict.get('endTime', None)
  311. unit_time = request_dict.get('timeUnit', None)
  312. if not all([start_time, end_time, unit_time]):
  313. return response.json(444, {'error param': 'startTime or endTime or timeUnit'})
  314. s_time = datetime.datetime.fromtimestamp(int(start_time))
  315. e_time = datetime.datetime.fromtimestamp(int(end_time))
  316. time_list = CommonService.cutting_time(s_time, e_time, unit_time)
  317. try:
  318. device_info_summary_qs = DeviceInfoSummary.objects.filter(
  319. time__gte=start_time, time__lt=end_time, query_type=1).values('country', 'count')
  320. count_all = device_info_summary_qs.aggregate(total=Sum('count'))['total']
  321. count_all = count_all if count_all else 0
  322. video_list = []
  323. region_list = []
  324. region_dict = {}
  325. for item in device_info_summary_qs:
  326. region_temp_dict = eval(item['country'])
  327. for country, count in region_temp_dict.items():
  328. if country in region_dict:
  329. region_dict[country] += count
  330. else:
  331. region_dict[country] = count
  332. for item in time_list:
  333. deivce_type_qs = device_info_summary_qs.filter(time__gte=item[0], time__lt=item[1]).values('count')
  334. count = deivce_type_qs.aggregate(total=Sum('count'))['total']
  335. count = count if count else 0
  336. rate = round(count / count_all * 100, 2) if count_all else 0
  337. vod_dict = {
  338. 'count': count,
  339. 'rate': rate,
  340. 'startTime': item[0],
  341. 'endTime': item[1]
  342. }
  343. video_list.append(vod_dict)
  344. for country, count in region_dict.items():
  345. rate = round(count / count_all * 100, 2) if count_all else 0
  346. region_list.append({
  347. 'countryName': country,
  348. 'count': count,
  349. 'rate': rate
  350. })
  351. res = {
  352. 'vodHls': video_list,
  353. 'region': CommonService.list_sort(region_list)
  354. }
  355. return response.json(0, res)
  356. except Exception as e:
  357. print(e)
  358. return response.json(500)
  359. @classmethod
  360. def add_device(cls, request_dict, response):
  361. """
  362. 查询设备增长数据
  363. @param request_dict:请求参数
  364. @request_dict starTime:开始时间
  365. @request_dict endTime:结束时间
  366. @param response:响应对象
  367. """
  368. start_time = request_dict.get('startTime', None) # 时间戳
  369. end_time = request_dict.get('endTime', None)
  370. unit_time = request_dict.get('timeUnit', None)
  371. if not all([start_time, end_time, unit_time]):
  372. return response.json(444, {'error param': 'startTime or endTime or timeUnit'})
  373. try:
  374. device_info_qs = DeviceInfoSummary.objects.filter(time__gte=start_time, time__lt=end_time,
  375. query_type=0).values(
  376. 'count', 'country', 'device_type', 'vod_service')
  377. count_all = device_info_qs.aggregate(total=Sum('count'))['total']
  378. count_all = count_all if count_all else 0
  379. region_dict = {}
  380. type_dict = {}
  381. vod_dict = {}
  382. for item in device_info_qs:
  383. region_temp_dict = eval(item['country'])
  384. type_temp_dict = eval(item['device_type'])
  385. vod_temp_dict = eval(item['vod_service'])
  386. for k, v in region_temp_dict.items():
  387. if k in region_dict:
  388. region_dict[k] += v
  389. else:
  390. region_dict[k] = v
  391. for k, v in type_temp_dict.items():
  392. if k in type_dict:
  393. type_dict[k] += v
  394. else:
  395. type_dict[k] = v
  396. for k, v in vod_temp_dict.items():
  397. if k in vod_dict:
  398. vod_dict[k] += v
  399. else:
  400. vod_dict[k] = v
  401. # 统计该时间段的设备数量(已去重)
  402. info_list = []
  403. start_time = datetime.datetime.fromtimestamp(int(start_time))
  404. end_time = datetime.datetime.fromtimestamp(int(end_time))
  405. time_list = CommonService.cutting_time(start_time, end_time, unit_time)
  406. for item in time_list:
  407. device_uid_qs = device_info_qs.filter(time__gte=item[0], time__lt=item[1])
  408. count = device_uid_qs.aggregate(total=Sum('count'))['total']
  409. count = count if count else 0
  410. rate = round(count / count_all * 100, 2) if count_all else 0
  411. info_dict = {
  412. 'startTime': item[0],
  413. 'endTime': item[1],
  414. 'count': count,
  415. 'rate': rate
  416. }
  417. info_list.append(info_dict)
  418. # 统计地区设备数量
  419. region_list = []
  420. for x, y in region_dict.items():
  421. rate = round(y / count_all * 100, 2) if count_all else 0
  422. region_list.append({
  423. 'countryName': x,
  424. 'count': y,
  425. 'rate': rate
  426. })
  427. # 统计设备类型数量
  428. type_list = []
  429. for x, y in type_dict.items():
  430. rate = round(y / count_all * 100, 2) if count_all else 0
  431. type_list.append({
  432. 'type': x,
  433. 'count': y,
  434. 'rate': rate
  435. })
  436. # 云存版本数量
  437. vod_list = []
  438. for x, y in vod_dict.items():
  439. rate = round(y / count_all * 100, 2) if count_all else 0
  440. vod_list.append({
  441. 'type': x,
  442. 'count': y,
  443. 'rate': rate
  444. })
  445. res = {
  446. 'addDevice': info_list,
  447. 'region': CommonService.list_sort(region_list),
  448. 'type': CommonService.list_sort(type_list),
  449. 'version': CommonService.list_sort(vod_list)
  450. }
  451. return response.json(0, res)
  452. except Exception as e:
  453. print(e)
  454. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  455. @classmethod
  456. def regional_statistics(cls, response):
  457. """
  458. 统计地区设备数量
  459. @param response:响应对象
  460. """
  461. all_device_qs = DeviceInfoSummary.objects.filter(query_type=0).values('continent', 'count', 'country')
  462. country_count = all_device_qs.aggregate(total=Sum('count'))['total']
  463. try:
  464. continent_list = []
  465. country_list = []
  466. continent_dict = {}
  467. country_dict = {}
  468. for item in all_device_qs:
  469. country_temp_dict = eval(item['country'])
  470. continent_temp_dict = eval(item['continent'])
  471. for x, y in country_temp_dict.items():
  472. if x in country_dict:
  473. country_dict[x] += y
  474. else:
  475. country_dict[x] = y
  476. for x, y in continent_temp_dict.items():
  477. if x in continent_dict:
  478. continent_dict[x] += y
  479. else:
  480. continent_dict[x] = y
  481. # 地区设备量前30
  482. for country, count in country_dict.items():
  483. rate = round(count / country_count * 100, 2) if country_count else 0
  484. country_list.append({
  485. 'countryName': country,
  486. 'count': count,
  487. 'rate': rate
  488. })
  489. for continent, count in continent_dict.items():
  490. rate = round(count / country_count * 100, 2) if country_count else 0
  491. continent_list.append({
  492. 'continentName': continent,
  493. 'count': count,
  494. 'rate': rate
  495. })
  496. res = {
  497. 'countries': CommonService.list_sort(country_list),
  498. 'continent': CommonService.list_sort(continent_list)
  499. }
  500. return response.json(0, res)
  501. except Exception as e:
  502. print(e)
  503. return response.json(500)
  504. @classmethod
  505. def type_statistics(cls, response):
  506. """
  507. 统计设备类型
  508. @param response:响应对象
  509. @return:
  510. """
  511. all_device_qs = DeviceInfoSummary.objects.filter(query_type=0).values('device_type', 'count')
  512. if not all_device_qs.exists():
  513. return response.json(173)
  514. count_all = all_device_qs.aggregate(total=Sum('count'))['total']
  515. try:
  516. device_type_list = []
  517. device_type_dict = {}
  518. for item in all_device_qs:
  519. country_temp_dict = eval(item['device_type'])
  520. for k, v in country_temp_dict.items():
  521. if k in device_type_dict:
  522. device_type_dict[k] += v
  523. else:
  524. device_type_dict[k] = v
  525. for x, y in device_type_dict.items():
  526. rate = round(y / count_all * 100, 2) if count_all else 0
  527. device_type_list.append({
  528. 'type': x,
  529. 'count': y,
  530. 'rate': rate
  531. })
  532. res = {
  533. 'type': CommonService.list_sort(device_type_list)
  534. }
  535. return response.json(0, res)
  536. except Exception as e:
  537. print(e)
  538. return response.json(500)