DeviceDataController.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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
  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. order_type = request_dict.get('orderType', None)
  151. if not order_type:
  152. return response.json(444)
  153. order_type = int(order_type)
  154. order_type_qs = Order_Model.objects.filter(order_type=order_type).values('UID').order_by('UID').distinct()
  155. try:
  156. order_type_list = []
  157. for order in order_type_qs:
  158. UID = order['UID']
  159. device_info_qs = Device_Info.objects.filter(UID=UID).values('Type').order_by('Type').distinct()
  160. if not device_info_qs.exists():
  161. continue
  162. device_info_qs = device_info_qs[0]['Type']
  163. order_type_list.append(device_info_qs)
  164. type_list = []
  165. for i in order_type_list:
  166. if i not in type_list:
  167. type_list.append(i)
  168. return response.json(0, type_list)
  169. except Exception as e:
  170. print(e)
  171. return response.json(500)
  172. @classmethod
  173. def add_device(cls, request_dict, response):
  174. """
  175. 查询设备增长数据
  176. @param request_dict:请求参数
  177. @request_dict starTime:开始时间
  178. @request_dict endTime:结束时间
  179. @param response:响应对象
  180. """
  181. start_time = request_dict.get('startTime', None) # 时间戳
  182. end_time = request_dict.get('endTime', None)
  183. unit_time = request_dict.get('unitTime', None)
  184. order_type = request_dict.get('orderType', None)
  185. if not all([start_time, end_time, unit_time, order_type]):
  186. return response.json(444, {'error param': 'startTime or endTime or timeUnit or order_type'})
  187. order_type = int(order_type)
  188. start_time = datetime.datetime.fromtimestamp(int(start_time))
  189. end_time = datetime.datetime.fromtimestamp(int(end_time))
  190. time_list = CommonService.cutting_time(start_time, end_time, unit_time)
  191. try:
  192. device_info_qs = Device_Info.objects.filter(data_joined__range=(start_time, end_time))
  193. device_test_qs = Device_Info.objects.filter(data_joined__lt=start_time)
  194. device_test = list(device_test_qs.values('UID').order_by('UID').distinct())
  195. device_info = list(device_info_qs.values('UID').order_by('UID').distinct())
  196. test_list = [item[key] for item in device_test for key in item]
  197. device_info_list = [item[key] for item in device_info for key in item]
  198. part_only_list = list(set(device_info_list) - set(test_list))
  199. count_all = len(part_only_list)
  200. count_all = int(count_all)
  201. # 统计该时间段的设备数量(已去重)
  202. res = {
  203. 'addDevice': '',
  204. 'region': '',
  205. 'type': '',
  206. 'version': '',
  207. }
  208. info_list = []
  209. region_list = []
  210. type_list = []
  211. version_list = []
  212. for item in time_list:
  213. start_time = datetime.datetime.fromtimestamp(int(item[0]))
  214. end_time = datetime.datetime.fromtimestamp(int(item[1]))
  215. device_qs = device_info_qs.filter(data_joined__range=(start_time, end_time))
  216. device_test_qs = Device_Info.objects.filter(data_joined__lt=start_time)
  217. device_test = list(device_test_qs.values('UID').order_by('UID').distinct())
  218. device_info = list(device_qs.values('UID').order_by('UID').distinct())
  219. test_list = [item[key] for item in device_test for key in item]
  220. device_info_list = [item[key] for item in device_info for key in item]
  221. part_only_list = list(set(device_info_list) - set(test_list))
  222. count_part = len(part_only_list)
  223. rate = round(count_part / count_all * 100, 2)
  224. info_dict = {
  225. 'count': len(part_only_list),
  226. 'startTime': item[0],
  227. 'endTime': item[1],
  228. 'rate': rate
  229. }
  230. info_list.append(info_dict)
  231. res['addDevice'] = info_list
  232. # 统计地区设备数量
  233. device_info_country_qs = device_info_qs.filter(UID__in=part_only_list).values('userID__region_country').annotate(
  234. count=Count('userID__region_country')).order_by('-count')
  235. for item in device_info_country_qs:
  236. country_id = item['userID__region_country']
  237. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'id')
  238. country_name = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
  239. country_qs = device_info_qs.filter(UID__in=part_only_list).values('UID').order_by('UID').distinct().values(
  240. 'userID__region_country')
  241. total_list = [item[key] for item in country_qs for key in item]
  242. country_count = total_list.count(country_id)
  243. rate = round(country_count / count_part * 100, 2)
  244. country_dict = {
  245. 'countryName': country_name,
  246. 'count': country_count,
  247. 'rate': rate
  248. # 'rate': rate
  249. }
  250. region_list.append(country_dict)
  251. res['region'] = CommonService.list_sort(region_list)
  252. # 统计设备类型数量
  253. device_info_type_qs = device_info_qs.filter(UID__in=part_only_list).values('Type').annotate(
  254. count=Count('Type', distinct=True)).order_by('-count').distinct()
  255. count = device_info_type_qs.count()
  256. for device_type in device_info_type_qs:
  257. type = device_type['Type']
  258. name = DEVICE_TYPE.get(type, '未知类型')
  259. name = name if name != 'UNKOWN' else '未知类型'
  260. type_qs = device_info_qs.filter(UID__in=part_only_list).values('UID').order_by('UID').distinct().values(
  261. 'Type')
  262. # rate = round(total / count_unique * 100, 2) # count_unique 有误,跟device_info_type_qs 总数合不上 (可以看151行)
  263. test_list = [item[key] for item in type_qs for key in item]
  264. type_count = test_list.count(type)
  265. rate = round(type_count / count_part * 100, 2)
  266. type_dict = {
  267. 'type': name,
  268. 'count': type_count,
  269. 'rate': rate
  270. # 'rate': rate
  271. }
  272. type_list.append(type_dict)
  273. res['type'] = CommonService.list_sort(type_list)
  274. # 统计设备版本数量
  275. order_model_qs = Order_Model.objects.filter(UID__in=part_only_list).values('UID').annotate(
  276. count=Count('UID', distinct=True))
  277. uid_qs = order_model_qs.values('UID').order_by('UID').distinct()
  278. order_model_qs = order_model_qs.values('order_type').order_by('order_type')
  279. # count = order_model_qs.count()
  280. order_type_list = []
  281. for order_model in order_model_qs:
  282. orderType = order_model['order_type']
  283. order_type_list.append(orderType)
  284. res_part = {}
  285. if order_type == 0:
  286. res_part['name'] = '云存'
  287. elif order_type == 1:
  288. res_part['name'] = 'AI'
  289. elif order_type == 2:
  290. res_part['name'] = '联通4G'
  291. res_part['total'] = order_type_list.count(order_type)
  292. res_part['rate'] = round(res_part['total'] / count_part * 100, 2)
  293. version_list.append(res_part)
  294. res['version'] = version_list
  295. return response.json(0, res)
  296. except Exception as e:
  297. print(e)
  298. return response.json(500, repr(e))
  299. @classmethod
  300. def regional_statistics(cls, response):
  301. """
  302. 统计地区设备数量
  303. @param response:响应对象
  304. """
  305. device_country_qs = Device_Info.objects.all().values('userID__region_country').annotate(
  306. count=Count('userID__region_country')).order_by('-count')
  307. device_info_qs = Device_Info.objects.values('UID').order_by('UID').distinct()
  308. count = device_info_qs.count()
  309. if not device_country_qs.exists():
  310. return response.json(444)
  311. res = {}
  312. try:
  313. device_country_list = []
  314. continent_list = []
  315. for device_country in device_country_qs:
  316. country_id = device_country['userID__region_country']
  317. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'region__name')
  318. if not country_qs.exists():
  319. name = '未知地区'
  320. else:
  321. name = country_qs[0]['country_name']
  322. count = Device_Info.objects.filter(
  323. userID__region_country=device_country['userID__region_country']).values('UID').annotate(
  324. count=Count('UID', distinct=True)).order_by('-count').count()
  325. device_country_list.append({
  326. 'countryName': name,
  327. 'count': count
  328. })
  329. if country_qs.exists():
  330. flag = 0
  331. for each in continent_list:
  332. if country_qs[0]['region__name'] == each['continentName']:
  333. each['count'] += count
  334. flag = 1
  335. break
  336. if flag == 0:
  337. continent_list.append({
  338. 'continentName': country_qs[0]['region__name'],
  339. 'count': count
  340. })
  341. for item in continent_list:
  342. item['rate'] = round(item['count'] / count * 100, 2)
  343. res['countries'] = device_country_list
  344. res['continent'] = continent_list
  345. return response.json(0, res)
  346. except Exception as e:
  347. print(e)
  348. return response.json(500)
  349. @classmethod
  350. def type_statistics(cls, response):
  351. """
  352. 统计设备类型
  353. @param response:响应对象
  354. @return:
  355. """
  356. device_info_qs = Device_Info.objects.all().values('Type').annotate(count=Count('Type')).order_by('-count')
  357. if not device_info_qs.exists():
  358. return response.json(444)
  359. res = {}
  360. try:
  361. device_info_list = []
  362. for device_info in device_info_qs:
  363. type = device_info['Type']
  364. name = DEVICE_TYPE.get(type, '未知类型')
  365. name = name if name != 'UNKOWN' else '未知类型'
  366. count = Device_Info.objects.filter(Type=device_info['Type']).values('UID').annotate(
  367. count=Count('UID', distinct=True)).order_by('-count').count()
  368. device_info_list.append({
  369. 'type': name,
  370. 'count': count
  371. })
  372. device_country_qs = Device_Info.objects.all().values('userID__region_country').annotate(
  373. count=Count('userID__region_country')).order_by('-count')
  374. device_country_list = []
  375. for device_country in device_country_qs:
  376. country_id = device_country['userID__region_country']
  377. country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'region__name')
  378. if not country_qs.exists():
  379. country_name = '未知地区'
  380. else:
  381. country_name = country_qs[0]['country_name']
  382. device_type_qs = Device_Info.objects.filter(userID__region_country=country_id).values('Type').annotate(
  383. count=Count('Type', distinct=True)).order_by('-count')
  384. country_type_list = []
  385. for device_type in device_type_qs:
  386. type = device_type['Type']
  387. name = DEVICE_TYPE.get(type, '未知类型')
  388. name = name if name != 'UNKOWN' else '未知类型'
  389. count = device_type_qs.filter(Type=device_type['Type']).values('UID').annotate(
  390. count=Count('UID', distinct=True)).order_by('-count').count()
  391. country_type_list.append({
  392. 'type': name,
  393. 'count': count
  394. })
  395. count = Device_Info.objects.filter(
  396. userID__region_country=device_country['userID__region_country']).values('UID').annotate(
  397. count=Count('UID', distinct=True)).order_by('-count').count()
  398. device_country_list.append({
  399. 'countryName': country_name,
  400. 'count': count,
  401. 'countryType': country_type_list
  402. })
  403. res['type'] = device_info_list
  404. res['region'] = device_country_list
  405. return response.json(0, res)
  406. except Exception as e:
  407. print(e)
  408. return response.json(500)