DeviceDataController.py 24 KB

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