DeviceDataController.py 26 KB

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