DeviceDataController.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. else:
  43. return response.json(414)
  44. @classmethod
  45. def golbal_type(cls, request, request_dict, response):
  46. """
  47. 全球设备类型分布
  48. @param request:请求
  49. @param request_dict:请求参数
  50. @param response: 响应对象
  51. """
  52. url_list = CommonService.get_domain_name()
  53. try:
  54. headers = {
  55. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  56. }
  57. type_list = []
  58. type_count = 0
  59. for url in url_list:
  60. url = url + request.path.replace('global/', '')
  61. res = requests.get(url=url, params=request_dict, headers=headers)
  62. result = res.json()
  63. if result['result_code'] == 0:
  64. for item in result['result']['region']:
  65. flag = 0
  66. for each in type_list:
  67. if item['countryName'] == each['countryName']:
  68. each['count'] += item['count']
  69. type_count += item['count']
  70. each['countryType'] += item['countryType']
  71. type_count += item['countryType']
  72. flag = 1
  73. break
  74. if flag == 0:
  75. type_list.append(item)
  76. type_count += item['count']
  77. for item in type_list:
  78. item['rate'] = round(item['count'] / type_count * 100, 2)
  79. else:
  80. return response.json(result['result_code'])
  81. res = {
  82. 'type': CommonService.list_sort(type_list)
  83. }
  84. return response.json(0, res)
  85. except Exception as e:
  86. print(e)
  87. return response.json(500)
  88. @classmethod
  89. def global_regional(cls, request, request_dict, response):
  90. """
  91. 全球设备分布
  92. @param request:请求
  93. @param request_dict:请求参数
  94. @param response:响应对象
  95. @return:
  96. """
  97. url_list = CommonService.get_domain_name()
  98. try:
  99. headers = {
  100. 'Authorization': request.META.get('HTTP_AUTHORIZATION')
  101. }
  102. device_list = []
  103. device_count = 0
  104. region_list = []
  105. region_count = 0
  106. for url in url_list:
  107. url = url + request.path.replace('global/', '')
  108. res = requests.get(url=url, params=request_dict, headers=headers)
  109. result = res.json()
  110. if result['result_code'] == 0:
  111. # 处理地区
  112. for item in result['result']['countries']:
  113. flag = 0
  114. for each in device_list:
  115. if each['countryName'] == item['countryName']:
  116. each['count'] += int(item['count'])
  117. device_count += int(item['count'])
  118. flag = 1
  119. break
  120. if flag == 0:
  121. device_list.append(item)
  122. device_count += int(item['count'])
  123. for item in device_list:
  124. rate = round(item['count'] / device_count * 100, 2)
  125. item['rate'] = rate
  126. for item in result['result']['continent']:
  127. flag = 0
  128. for each in region_list:
  129. if each['continentName'] == item['continentName']:
  130. each['count'] += item['count']
  131. region_count += item['count']
  132. flag = 1
  133. break
  134. if flag == 0:
  135. region_list.append(item)
  136. region_count += item['count']
  137. for item in region_list:
  138. item['rate'] = round(item['count'] / region_count * 100, 2)
  139. else:
  140. return response.json(result['result_code'])
  141. res = {
  142. 'countries': CommonService.list_sort(device_list[:20]),
  143. 'continent': region_list
  144. }
  145. return response.json(0, res)
  146. except Exception as e:
  147. return response.json(500, repr(e))
  148. @classmethod
  149. def device_active(cls, request_dict, response):
  150. start_time = request_dict.get('startTime', None) # 时间戳
  151. end_time = request_dict.get('endTime', None)
  152. unit_time = request_dict.get('unitTime', None)
  153. if not all([start_time, end_time, unit_time]):
  154. return response.json(444, {'error param': 'startTime or endTime or timeUnit or order_type'})
  155. s_time = datetime.datetime.fromtimestamp(int(start_time))
  156. e_time = datetime.datetime.fromtimestamp(int(end_time))
  157. time_list = CommonService.cutting_time(s_time, e_time, unit_time)
  158. try:
  159. vod_hls_model_qs = VodHlsModel.objects.filter(time__range=(start_time, end_time))
  160. device_info = list(vod_hls_model_qs.values('uid').order_by('uid').distinct())
  161. device_info_list = [item[key] for item in device_info for key in item]
  162. count_all = len(device_info_list)
  163. res = {}
  164. vod_list = []
  165. region_list = []
  166. for item in time_list:
  167. vod_hls_qs = vod_hls_model_qs.filter(time__range=(item[0], item[1]))
  168. uid_qs = vod_hls_qs.values('uid').order_by('uid').distinct()
  169. uid_list = [item[key] for item in uid_qs for key in item]
  170. rate = round(uid_qs.count() / count_all * 100, 2)
  171. vod_dict = {
  172. 'count': uid_qs.count(),
  173. 'rate': rate,
  174. 'startTime': item[0],
  175. 'endTime': item[1]
  176. }
  177. vod_list.append(vod_dict)
  178. res['vodHls'] = vod_list
  179. type_country_qs = Device_Info.objects.filter(UID__in=uid_list).values(
  180. 'userID__region_country').annotate(count=Count('userID__region_country')).order_by('-count')
  181. for item in type_country_qs:
  182. country_id = item['userID__region_country']
  183. country_qs = CountryModel.objects.filter(id=country_id).values('country_name')
  184. country_name = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
  185. country_qs = vod_hls_model_qs.filter(uid__in=uid_list).values('uid').order_by(
  186. 'uid').distinct()
  187. total_list = [item[key] for item in country_qs for key in item]
  188. country_count = len(total_list)
  189. rate = round(country_count / count_all * 100, 2)
  190. country_dict = {
  191. 'countryName': country_name,
  192. 'count': item['count'],
  193. 'rate': rate
  194. }
  195. region_list.append(country_dict)
  196. res['region'] = region_list
  197. return response.json(0, res)
  198. except Exception as e:
  199. print(e)
  200. return response.json(500)
  201. @classmethod
  202. def add_device(cls, request_dict, response):
  203. """
  204. 查询设备增长数据
  205. @param request_dict:请求参数
  206. @request_dict starTime:开始时间
  207. @request_dict endTime:结束时间
  208. @param response:响应对象
  209. """
  210. start_time = request_dict.get('startTime', None) # 时间戳
  211. end_time = request_dict.get('endTime', None)
  212. unit_time = request_dict.get('unitTime', None)
  213. order_type = request_dict.get('orderType', None)
  214. if not all([start_time, end_time, unit_time, order_type]):
  215. return response.json(444, {'error param': 'startTime or endTime or timeUnit or order_type'})
  216. order_type = int(order_type)
  217. start_time = datetime.datetime.fromtimestamp(int(start_time))
  218. end_time = datetime.datetime.fromtimestamp(int(end_time))
  219. time_list = CommonService.cutting_time(start_time, end_time, unit_time)
  220. try:
  221. device_info_qs = Device_Info.objects.filter(data_joined__range=(start_time, end_time))
  222. device_test_qs = Device_Info.objects.filter(data_joined__lt=start_time)
  223. device_test = list(device_test_qs.values('UID').order_by('UID').distinct())
  224. device_info = list(device_info_qs.values('UID').order_by('UID').distinct())
  225. test_list = [item[key] for item in device_test for key in item]
  226. device_info_list = [item[key] for item in device_info for key in item]
  227. part_only_list = list(set(device_info_list) - set(test_list))
  228. count_all = len(part_only_list)
  229. count_all = int(count_all)
  230. # 统计该时间段的设备数量(已去重)
  231. res = {
  232. 'addDevice': '',
  233. 'region': '',
  234. 'type': '',
  235. 'version': '',
  236. }
  237. info_list = []
  238. region_list = []
  239. type_list = []
  240. version_list = []
  241. for item in time_list:
  242. start_time = datetime.datetime.fromtimestamp(int(item[0]))
  243. end_time = datetime.datetime.fromtimestamp(int(item[1]))
  244. device_qs = device_info_qs.filter(data_joined__range=(start_time, end_time))
  245. device_test_qs = Device_Info.objects.filter(data_joined__lt=start_time)
  246. device_test = list(device_test_qs.values('UID').order_by('UID').distinct())
  247. device_info = list(device_qs.values('UID').order_by('UID').distinct())
  248. test_list = [item[key] for item in device_test for key in item]
  249. device_info_list = [item[key] for item in device_info for key in item]
  250. part_only_list = list(set(device_info_list) - set(test_list))
  251. count_part = len(part_only_list)
  252. rate = round(count_part / count_all * 100, 2)
  253. info_dict = {
  254. 'count': len(part_only_list),
  255. 'startTime': item[0],
  256. 'endTime': item[1],
  257. 'rate': rate
  258. }
  259. info_list.append(info_dict)
  260. res['addDevice'] = info_list
  261. # 统计地区设备数量
  262. device_info_country_qs = device_info_qs.filter(UID__in=part_only_list).values(
  263. 'userID__region_country').annotate(
  264. count=Count('userID__region_country')).order_by('-count')
  265. for item in device_info_country_qs:
  266. country_id = item['userID__region_country']
  267. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'id')
  268. country_name = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
  269. country_qs = device_info_qs.filter(UID__in=part_only_list).values('UID').order_by(
  270. 'UID').distinct().values(
  271. 'userID__region_country')
  272. total_list = [item[key] for item in country_qs for key in item]
  273. country_count = total_list.count(country_id)
  274. rate = round(country_count / count_part * 100, 2)
  275. country_dict = {
  276. 'countryName': country_name,
  277. 'count': country_count,
  278. 'rate': rate
  279. # 'rate': rate
  280. }
  281. region_list.append(country_dict)
  282. res['region'] = CommonService.list_sort(region_list)
  283. # 统计设备类型数量
  284. device_info_type_qs = device_info_qs.filter(UID__in=part_only_list).values('Type').annotate(
  285. count=Count('Type', distinct=True)).order_by('-count').distinct()
  286. count = device_info_type_qs.count()
  287. for device_type in device_info_type_qs:
  288. type = device_type['Type']
  289. name = DEVICE_TYPE.get(type, '未知类型')
  290. name = name if name != 'UNKOWN' else '未知类型'
  291. type_qs = device_info_qs.filter(UID__in=part_only_list).values('UID').order_by(
  292. 'UID').distinct().values(
  293. 'Type')
  294. # rate = round(total / count_unique * 100, 2) # count_unique 有误,跟device_info_type_qs 总数合不上 (可以看151行)
  295. test_list = [item[key] for item in type_qs for key in item]
  296. type_count = test_list.count(type)
  297. rate = round(type_count / count_part * 100, 2)
  298. type_dict = {
  299. 'type': name,
  300. 'count': type_count,
  301. 'rate': rate
  302. # 'rate': rate
  303. }
  304. type_list.append(type_dict)
  305. res['type'] = CommonService.list_sort(type_list)
  306. # 统计设备版本数量
  307. order_model_qs = Order_Model.objects.filter(UID__in=part_only_list).values('UID').annotate(
  308. count=Count('UID', distinct=True))
  309. uid_qs = order_model_qs.values('UID').order_by('UID').distinct()
  310. order_model_qs = order_model_qs.values('order_type').order_by('order_type')
  311. # count = order_model_qs.count()
  312. order_type_list = []
  313. for order_model in order_model_qs:
  314. orderType = order_model['order_type']
  315. order_type_list.append(orderType)
  316. res_part = {}
  317. if order_type == 0:
  318. res_part['name'] = '云存'
  319. elif order_type == 1:
  320. res_part['name'] = 'AI'
  321. elif order_type == 2:
  322. res_part['name'] = '联通4G'
  323. res_part['total'] = order_type_list.count(order_type)
  324. res_part['rate'] = round(res_part['total'] / count_part * 100, 2)
  325. version_list.append(res_part)
  326. res['version'] = version_list
  327. return response.json(0, res)
  328. except Exception as e:
  329. print(e)
  330. return response.json(500, repr(e))
  331. @classmethod
  332. def regional_statistics(cls, response):
  333. """
  334. 统计地区设备数量
  335. @param response:响应对象
  336. """
  337. device_country_qs = Device_Info.objects.all().values('userID__region_country').annotate(
  338. count=Count('userID__region_country')).order_by('-count')
  339. device_info_qs = Device_Info.objects.values('UID').order_by('UID').distinct()
  340. count = device_info_qs.count()
  341. if not device_country_qs.exists():
  342. return response.json(444)
  343. res = {}
  344. try:
  345. device_country_list = []
  346. continent_list = []
  347. for device_country in device_country_qs:
  348. country_id = device_country['userID__region_country']
  349. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'region__name')
  350. if not country_qs.exists():
  351. name = '未知地区'
  352. else:
  353. name = country_qs[0]['country_name']
  354. count = Device_Info.objects.filter(
  355. userID__region_country=device_country['userID__region_country']).values('UID').annotate(
  356. count=Count('UID', distinct=True)).order_by('-count').count()
  357. device_country_list.append({
  358. 'countryName': name,
  359. 'count': count
  360. })
  361. if country_qs.exists():
  362. flag = 0
  363. for each in continent_list:
  364. if country_qs[0]['region__name'] == each['continentName']:
  365. each['count'] += count
  366. flag = 1
  367. break
  368. if flag == 0:
  369. continent_list.append({
  370. 'continentName': country_qs[0]['region__name'],
  371. 'count': count
  372. })
  373. for item in continent_list:
  374. item['rate'] = round(item['count'] / count * 100, 2)
  375. res['countries'] = device_country_list
  376. res['continent'] = continent_list
  377. return response.json(0, res)
  378. except Exception as e:
  379. print(e)
  380. return response.json(500)
  381. @classmethod
  382. def type_statistics(cls, response):
  383. """
  384. 统计设备类型
  385. @param response:响应对象
  386. @return:
  387. """
  388. device_info_qs = Device_Info.objects.all().values('Type').annotate(count=Count('Type')).order_by('-count')
  389. if not device_info_qs.exists():
  390. return response.json(444)
  391. res = {}
  392. try:
  393. device_info_list = []
  394. for device_info in device_info_qs:
  395. type = device_info['Type']
  396. name = DEVICE_TYPE.get(type, '未知类型')
  397. name = name if name != 'UNKOWN' else '未知类型'
  398. count = Device_Info.objects.filter(Type=device_info['Type']).values('UID').annotate(
  399. count=Count('UID', distinct=True)).order_by('-count').count()
  400. device_info_list.append({
  401. 'type': name,
  402. 'count': count
  403. })
  404. device_country_qs = Device_Info.objects.all().values('userID__region_country').annotate(
  405. count=Count('userID__region_country')).order_by('-count')
  406. device_country_list = []
  407. for device_country in device_country_qs:
  408. country_id = device_country['userID__region_country']
  409. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'region__name')
  410. if not country_qs.exists():
  411. country_name = '未知地区'
  412. else:
  413. country_name = country_qs[0]['country_name']
  414. device_type_qs = Device_Info.objects.filter(userID__region_country=country_id).values('Type').annotate(
  415. count=Count('Type', distinct=True)).order_by('-count')
  416. country_type_list = []
  417. for device_type in device_type_qs:
  418. type = device_type['Type']
  419. name = DEVICE_TYPE.get(type, '未知类型')
  420. name = name if name != 'UNKOWN' else '未知类型'
  421. count = device_type_qs.filter(Type=device_type['Type']).values('UID').annotate(
  422. count=Count('UID', distinct=True)).order_by('-count').count()
  423. country_type_list.append({
  424. 'type': name,
  425. 'count': count
  426. })
  427. count = Device_Info.objects.filter(
  428. userID__region_country=device_country['userID__region_country']).values('UID').annotate(
  429. count=Count('UID', distinct=True)).order_by('-count').count()
  430. device_country_list.append({
  431. 'countryName': country_name,
  432. 'count': count,
  433. 'countryType': country_type_list
  434. })
  435. res['type'] = device_info_list
  436. res['region'] = device_country_list
  437. return response.json(0, res)
  438. except Exception as e:
  439. print(e)
  440. return response.json(500)