DeviceDataController.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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']['region']:
  217. flag = 0
  218. for each in type_list:
  219. if item['countryName'] == each['countryName']:
  220. each['count'] += item['count']
  221. type_count += item['count']
  222. each['countryType'] += item['countryType']
  223. type_count += item['countryType']
  224. flag = 1
  225. break
  226. if flag == 0:
  227. type_list.append(item)
  228. type_count += item['count']
  229. for item in type_list:
  230. item['rate'] = round(item['count'] / type_count * 100, 2)
  231. else:
  232. return response.json(result['result_code'])
  233. res = {
  234. 'type': CommonService.list_sort(type_list)
  235. }
  236. return response.json(0, res)
  237. except Exception as e:
  238. print(e)
  239. return response.json(500)
  240. @classmethod
  241. def global_regional(cls, request, request_dict, response):
  242. """
  243. 全球设备分布
  244. @param request:请求
  245. @param request_dict:请求参数
  246. @param response:响应对象
  247. @return:
  248. """
  249. url_list = CommonService.get_domain_name()
  250. try:
  251. headers = {
  252. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  253. }
  254. device_list = []
  255. device_count = 0
  256. region_list = []
  257. region_count = 0
  258. for url in url_list:
  259. url = url + request.path.replace('global/', '')
  260. res = requests.get(url=url, params=request_dict, headers=headers)
  261. result = res.json()
  262. if result['result_code'] == 0:
  263. # 处理地区
  264. for item in result['result']['countries']:
  265. flag = 0
  266. for each in device_list:
  267. if each['countryName'] == item['countryName']:
  268. each['count'] += int(item['count'])
  269. device_count += int(item['count'])
  270. flag = 1
  271. break
  272. if flag == 0:
  273. device_list.append(item)
  274. device_count += int(item['count'])
  275. for item in device_list:
  276. rate = round(item['count'] / device_count * 100, 2)
  277. item['rate'] = rate
  278. for item in result['result']['continent']:
  279. flag = 0
  280. for each in region_list:
  281. if each['continentName'] == item['continentName']:
  282. each['count'] += item['count']
  283. region_count += item['count']
  284. flag = 1
  285. break
  286. if flag == 0:
  287. region_list.append(item)
  288. region_count += item['count']
  289. for item in region_list:
  290. item['rate'] = round(item['count'] / region_count * 100, 2)
  291. else:
  292. return response.json(result['result_code'])
  293. res = {
  294. 'countries': CommonService.list_sort(device_list[:20]),
  295. 'continent': region_list
  296. }
  297. return response.json(0, res)
  298. except Exception as e:
  299. return response.json(500, 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 or order_type'})
  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. vod_hls_model_qs = VodHlsModel.objects.filter(time__range=(start_time, end_time))
  319. if not vod_hls_model_qs.exists():
  320. return response.json(173)
  321. device_info = list(vod_hls_model_qs.values('uid').order_by('uid').distinct())
  322. device_info_list = [item[key] for item in device_info for key in item]
  323. count_all = len(device_info_list)
  324. res = {}
  325. vod_list = []
  326. region_list = []
  327. for item in time_list:
  328. vod_hls_qs = vod_hls_model_qs.filter(time__range=(item[0], item[1]))
  329. uid_qs = vod_hls_qs.values('uid').order_by('uid').distinct()
  330. uid_list = [item[key] for item in uid_qs for key in item]
  331. rate = round(uid_qs.count() / count_all * 100, 2)
  332. vod_dict = {
  333. 'count': uid_qs.count(),
  334. 'rate': rate,
  335. 'startTime': item[0],
  336. 'endTime': item[1]
  337. }
  338. vod_list.append(vod_dict)
  339. res['vodHls'] = vod_list
  340. type_country_qs = Device_Info.objects.filter(UID__in=uid_list).values(
  341. 'userID__region_country').annotate(count=Count('userID__region_country')).order_by('-count')
  342. for item in type_country_qs:
  343. country_id = item['userID__region_country']
  344. country_qs = CountryModel.objects.filter(id=country_id).values('country_name')
  345. country_name = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
  346. country_qs = vod_hls_model_qs.filter(uid__in=uid_list).values('uid').order_by(
  347. 'uid').distinct()
  348. total_list = [item[key] for item in country_qs for key in item]
  349. country_count = len(total_list)
  350. rate = round(country_count / count_all * 100, 2)
  351. country_dict = {
  352. 'countryName': country_name,
  353. 'count': item['count'],
  354. 'rate': rate
  355. }
  356. region_list.append(country_dict)
  357. res['region'] = region_list
  358. return response.json(0, res)
  359. except Exception as e:
  360. print(e)
  361. return response.json(500)
  362. @classmethod
  363. def add_device(cls, request_dict, response):
  364. """
  365. 查询设备增长数据
  366. @param request_dict:请求参数
  367. @request_dict starTime:开始时间
  368. @request_dict endTime:结束时间
  369. @param response:响应对象
  370. """
  371. start_time = request_dict.get('startTime', None) # 时间戳
  372. end_time = request_dict.get('endTime', None)
  373. unit_time = request_dict.get('timeUnit', None)
  374. order_type = request_dict.get('orderType', None)
  375. if not all([start_time, end_time, unit_time, order_type]):
  376. return response.json(444, {'error param': 'startTime or endTime or timeUnit or order_type'})
  377. order_type = int(order_type)
  378. start_time = datetime.datetime.fromtimestamp(int(start_time))
  379. end_time = datetime.datetime.fromtimestamp(int(end_time))
  380. time_list = CommonService.cutting_time(start_time, end_time, unit_time)
  381. try:
  382. device_info_qs = Device_Info.objects.filter(data_joined__range=(start_time, end_time))
  383. device_test_qs = Device_Info.objects.filter(data_joined__lt=start_time)
  384. device_test = list(device_test_qs.values('UID').order_by('UID').distinct())
  385. device_info = list(device_info_qs.values('UID').order_by('UID').distinct())
  386. test_list = [item[key] for item in device_test for key in item]
  387. device_info_list = [item[key] for item in device_info for key in item]
  388. part_only_list = list(set(device_info_list) - set(test_list))
  389. count_all = len(part_only_list)
  390. count_all = int(count_all)
  391. # 统计该时间段的设备数量(已去重)
  392. res = {
  393. 'addDevice': '',
  394. 'region': '',
  395. 'type': '',
  396. 'version': '',
  397. }
  398. info_list = []
  399. region_list = []
  400. type_list = []
  401. version_list = []
  402. for item in time_list:
  403. start_time = datetime.datetime.fromtimestamp(int(item[0]))
  404. end_time = datetime.datetime.fromtimestamp(int(item[1]))
  405. device_qs = device_info_qs.filter(data_joined__range=(start_time, end_time))
  406. device_test_qs = Device_Info.objects.filter(data_joined__lt=start_time)
  407. device_test = list(device_test_qs.values('UID').order_by('UID').distinct())
  408. device_info = list(device_qs.values('UID').order_by('UID').distinct())
  409. test_list = [item[key] for item in device_test for key in item]
  410. device_info_list = [item[key] for item in device_info for key in item]
  411. part_only_list = list(set(device_info_list) - set(test_list))
  412. count_part = len(part_only_list)
  413. rate = round(count_part / count_all * 100, 2)
  414. info_dict = {
  415. 'startTime': item[0],
  416. 'endTime': item[1],
  417. 'count': len(part_only_list),
  418. 'rate': rate
  419. }
  420. info_list.append(info_dict)
  421. res['addDevice'] = info_list
  422. # 统计地区设备数量
  423. device_info_country_qs = device_info_qs.filter(UID__in=part_only_list).values(
  424. 'userID__region_country').annotate(
  425. count=Count('userID__region_country')).order_by('-count')
  426. for item in device_info_country_qs:
  427. country_id = item['userID__region_country']
  428. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'id')
  429. country_name = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
  430. country_qs = device_info_qs.filter(UID__in=part_only_list).values('UID').order_by(
  431. 'UID').distinct().values(
  432. 'userID__region_country')
  433. total_list = [item[key] for item in country_qs for key in item]
  434. country_count = total_list.count(country_id)
  435. rate = round(country_count / count_part * 100, 2)
  436. country_dict = {
  437. 'countryName': country_name,
  438. 'count': country_count,
  439. 'rate': rate
  440. }
  441. region_list.append(country_dict)
  442. res['region'] = CommonService.list_sort(region_list)
  443. # 统计设备类型数量
  444. device_info_type_qs = device_info_qs.filter(UID__in=part_only_list).values('Type').annotate(
  445. count=Count('Type', distinct=True)).order_by('-count').distinct()
  446. count = device_info_type_qs.count()
  447. for device_type in device_info_type_qs:
  448. type = device_type['Type']
  449. name = DEVICE_TYPE.get(type, '未知类型')
  450. name = name if name != 'UNKOWN' else '未知类型'
  451. type_qs = device_info_qs.filter(UID__in=part_only_list).values('UID').order_by(
  452. 'UID').distinct().values(
  453. 'Type')
  454. test_list = [item[key] for item in type_qs for key in item]
  455. type_count = test_list.count(type)
  456. rate = round(type_count / count_part * 100, 2)
  457. type_dict = {
  458. 'type': name,
  459. 'count': type_count,
  460. 'rate': rate
  461. }
  462. type_list.append(type_dict)
  463. res['type'] = CommonService.list_sort(type_list)
  464. # 统计设备版本数量
  465. order_model_qs = Order_Model.objects.filter(UID__in=part_only_list).values('UID').annotate(
  466. count=Count('UID', distinct=True))
  467. order_model_qs = order_model_qs.filter(order_type=order_type).values('order_type', 'UID').order_by(
  468. 'UID')
  469. order_type_list = []
  470. for order_model in order_model_qs:
  471. orderType = order_model['UID']
  472. order_type_list.append(orderType)
  473. res_part = {}
  474. device_info_type_qs = device_info_qs.filter(UID__in=order_type_list).values('Type').annotate(
  475. count=Count('Type', distinct=True)).order_by('-count').distinct()
  476. for device_type in device_info_type_qs:
  477. type = device_type['Type']
  478. name = DEVICE_TYPE.get(type, '未知类型')
  479. res_part['type'] = name if name != 'UNKOWN' else '未知类型'
  480. type_qs = device_info_qs.filter(UID__in=order_type_list).values('UID').order_by(
  481. 'UID').distinct().values(
  482. 'Type')
  483. test_list = [item[key] for item in type_qs for key in item]
  484. res_part['count'] = test_list.count(type)
  485. res_part['rate'] = round(res_part['count'] / count_part * 100, 2)
  486. version_list.append(res_part)
  487. res['version'] = version_list
  488. return response.json(0, res)
  489. except Exception as e:
  490. print(e)
  491. return response.json(500, repr(e))
  492. @classmethod
  493. def regional_statistics(cls, response):
  494. """
  495. 统计地区设备数量
  496. @param response:响应对象
  497. """
  498. device_country_qs = Device_Info.objects.all().values('userID__region_country').annotate(
  499. count=Count('userID__region_country')).order_by('-count')
  500. device_info_qs = Device_Info.objects.values('UID').order_by('UID').distinct()
  501. count = device_info_qs.count()
  502. if not device_country_qs.exists():
  503. return response.json(444)
  504. res = {}
  505. try:
  506. device_country_list = []
  507. continent_list = []
  508. for device_country in device_country_qs:
  509. country_id = device_country['userID__region_country']
  510. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'region__name')
  511. if not country_qs.exists():
  512. name = '未知地区'
  513. else:
  514. name = country_qs[0]['country_name']
  515. count = Device_Info.objects.filter(
  516. userID__region_country=device_country['userID__region_country']).values('UID').annotate(
  517. count=Count('UID', distinct=True)).order_by('-count').count()
  518. device_country_list.append({
  519. 'countryName': name,
  520. 'count': count
  521. })
  522. if country_qs.exists():
  523. flag = 0
  524. for each in continent_list:
  525. if country_qs[0]['region__name'] == each['continentName']:
  526. each['count'] += count
  527. flag = 1
  528. break
  529. if flag == 0:
  530. continent_list.append({
  531. 'continentName': country_qs[0]['region__name'],
  532. 'count': count
  533. })
  534. for item in continent_list:
  535. item['rate'] = round(item['count'] / count * 100, 2)
  536. res['countries'] = device_country_list
  537. res['continent'] = continent_list
  538. return response.json(0, res)
  539. except Exception as e:
  540. print(e)
  541. return response.json(500)
  542. @classmethod
  543. def type_statistics(cls, response):
  544. """
  545. 统计设备类型
  546. @param response:响应对象
  547. @return:
  548. """
  549. device_info_qs = Device_Info.objects.all().values('Type').annotate(count=Count('Type')).order_by('-count')
  550. if not device_info_qs.exists():
  551. return response.json(444)
  552. res = {}
  553. try:
  554. device_info_list = []
  555. for device_info in device_info_qs:
  556. type = device_info['Type']
  557. name = DEVICE_TYPE.get(type, '未知类型')
  558. name = name if name != 'UNKOWN' else '未知类型'
  559. count = Device_Info.objects.filter(Type=device_info['Type']).values('UID').annotate(
  560. count=Count('UID', distinct=True)).order_by('-count').count()
  561. device_info_list.append({
  562. 'type': name,
  563. 'count': count
  564. })
  565. device_country_qs = Device_Info.objects.all().values('userID__region_country').annotate(
  566. count=Count('userID__region_country')).order_by('-count')
  567. device_country_list = []
  568. for device_country in device_country_qs:
  569. country_id = device_country['userID__region_country']
  570. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'region__name')
  571. if not country_qs.exists():
  572. country_name = '未知地区'
  573. else:
  574. country_name = country_qs[0]['country_name']
  575. device_type_qs = Device_Info.objects.filter(userID__region_country=country_id).values('Type').annotate(
  576. count=Count('Type', distinct=True)).order_by('-count')
  577. country_type_list = []
  578. for device_type in device_type_qs:
  579. type = device_type['Type']
  580. name = DEVICE_TYPE.get(type, '未知类型')
  581. name = name if name != 'UNKOWN' else '未知类型'
  582. count = device_type_qs.filter(Type=device_type['Type']).values('UID').annotate(
  583. count=Count('UID', distinct=True)).order_by('-count').count()
  584. country_type_list.append({
  585. 'type': name,
  586. 'count': count
  587. })
  588. count = Device_Info.objects.filter(
  589. userID__region_country=device_country['userID__region_country']).values('UID').annotate(
  590. count=Count('UID', distinct=True)).order_by('-count').count()
  591. device_country_list.append({
  592. 'countryName': country_name,
  593. 'count': count,
  594. 'countryType': country_type_list
  595. })
  596. res['type'] = device_info_list
  597. res['region'] = device_country_list
  598. return response.json(0, res)
  599. except Exception as e:
  600. print(e)
  601. return response.json(500)