123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600 |
- # -*- encoding: utf-8 -*-
- """
- @File : UserDataController.py
- @Time : 2022/8/16 10:44
- @Author : peng
- @Email : zhangdongming@asj6.wecom.work
- @Software: PyCharm
- """
- import datetime
- import requests
- from django.db.models import Q, Sum
- from django.views.generic.base import View
- from Model.models import CountryModel, UidSetModel, DeviceInfoSummary
- from Service.CommonService import CommonService
- # 设备数据
- class DeviceDataView(View):
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.GET, request, operation)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.POST, request, operation)
- def validation(self, request_dict, request, operation):
- token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
- if token_code != 0:
- return response.json(token_code)
- if operation == 'type': # 统计设备类型
- return self.type_statistics(response)
- if operation == 'regional': # 设备地区分布
- return self.regional_statistics(response)
- if operation == 'addDevice': # 查询设备增长数据(数据有些许差异)
- return self.add_device(request_dict, response)
- if operation == 'active': # 设备活跃数据
- return self.device_active(request_dict, response)
- if operation == 'global/regional': # 全球设备分布
- return self.global_regional(request, request_dict, response)
- if operation == 'global/type': # 全球设备类型
- return self.golbal_type(request, request_dict, response)
- if operation == 'global/active': # 全球设备活跃分布
- return self.golbal_active(request, request_dict, response)
- if operation == 'global/addDevice': # 全球新增设备数据
- return self.golbal_add_device(request, request_dict, response)
- if operation == 'ip/country': #
- return self.ip_country(response)
- else:
- return response.json(414)
- @staticmethod
- def ip_country(response):
- uid_set_qs = UidSetModel.objects.filter(~Q(ip='') & Q(tb_country=0)).values('ip')
- for uid_set in uid_set_qs:
- ip = uid_set['ip']
- ipInfo = CommonService.getIpIpInfo(ip, 'CN')
- country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
- if country_qs.exists():
- country = country_qs[0]['id']
- uid_set_qs.filter(ip=ip).update(tb_country=country)
- return response.json(0)
- @classmethod
- def golbal_add_device(cls, request, request_dict, response):
- """
- 全球新增设备数据
- @param request:请求
- @param request_dict:请求参数
- @param response: 响应对象
- """
- url_list = CommonService.get_domain_name()
- try:
- headers = {
- 'Authorization': request.META.get('HTTP_AUTHORIZATION')
- }
- device_list = []
- device_count = 0
- type_list = []
- type_count = 0
- region_list = []
- region_count = 0
- order_list = []
- order_count = 0
- for url in url_list:
- url = url + request.path.replace('global/', '')
- res = requests.get(url=url, params=request_dict, headers=headers)
- result = res.json()
- if result['result_code'] == 0:
- for item in result['result']['addDevice']:
- flag = 0
- for each in device_list:
- if item['startTime'] == each['startTime'] and item['endTime'] == each['endTime']:
- each['count'] += item['count']
- device_count += item['count']
- flag = 1
- break
- if flag == 0:
- device_list.append(item)
- device_count += item['count']
- for item in device_list:
- if device_count != 0:
- item['rate'] = round(item['count'] / device_count * 100, 2)
- else:
- break
- for item in result['result']['region']:
- flag = 0
- for each in region_list:
- if item['countryName'] == each['countryName']:
- each['count'] += item['count']
- region_count += item['count']
- flag = 1
- break
- if flag == 0:
- region_list.append(item)
- region_count += item['count']
- for item in region_list:
- if region_count != 0:
- item['rate'] = round(item['count'] / region_count * 100, 2)
- else:
- break
- for item in result['result']['type']:
- flag = 0
- for each in type_list:
- if item['type'] == each['type']:
- each['count'] += item['count']
- type_count += item['count']
- flag = 1
- break
- if flag == 0:
- type_list.append(item)
- type_count += item['count']
- for item in type_list:
- if type_count != 0:
- item['rate'] = round(item['count'] / type_count * 100, 2)
- else:
- break
- for item in result['result']['version']:
- flag = 0
- for each in order_list:
- if item['type'] == each['type']:
- each['count'] += item['count']
- order_count += item['count']
- flag = 1
- break
- if flag == 0:
- order_list.append(item)
- order_count += item['count']
- for item in order_list:
- if order_count != 0:
- item['rate'] = round(item['count'] / order_count * 100, 2)
- else:
- break
- else:
- return response.json(result['result_code'])
- res = {
- 'device': device_list,
- 'type': type_list,
- 'region': CommonService.list_sort(region_list),
- 'version': order_list
- }
- return response.json(0, res)
- except Exception as e:
- print(e)
- return response.json(500, repr(e))
- @classmethod
- def golbal_active(cls, request, request_dict, response):
- """
- 全球设备活跃分布
- @param request:请求
- @param request_dict:请求参数
- @param response: 响应对象
- """
- url_list = CommonService.get_domain_name()
- try:
- headers = {
- 'Authorization': request.META.get('HTTP_AUTHORIZATION')
- }
- type_list = []
- type_count = 0
- region_list = []
- region_count = 0
- for url in url_list:
- url = url + request.path.replace('global/', '')
- res = requests.get(url=url, params=request_dict, headers=headers)
- result = res.json()
- if result['result_code'] == 0:
- for item in result['result']['vodHls']:
- flag = 0
- for each in type_list:
- if item['startTime'] == each['startTime'] and item['endTime'] == each['endTime']:
- each['count'] += item['count']
- type_count += item['count']
- flag = 1
- break
- if flag == 0:
- type_list.append(item)
- type_count += item['count']
- for item in type_list:
- if type_count != 0:
- item['rate'] = round(item['count'] / type_count * 100, 2)
- else:
- break
- for item in result['result']['region']:
- flag = 0
- for each in region_list:
- if item['countryName'] == each['countryName']:
- each['count'] += item['count']
- region_count += item['count']
- flag = 1
- break
- if flag == 0:
- region_list.append(item)
- region_count += item['count']
- for item in region_list:
- if region_count != 0:
- item['rate'] = round(item['count'] / region_count * 100, 2)
- else:
- break
- else:
- return response.json(result['result_code'])
- res = {
- 'device': type_list,
- 'region': CommonService.list_sort(region_list)
- }
- return response.json(0, res)
- except Exception as e:
- print(e)
- return response.json(500, repr(e))
- @classmethod
- def golbal_type(cls, request, request_dict, response):
- """
- 全球设备类型分布
- @param request:请求
- @param request_dict:请求参数
- @param response: 响应对象
- """
- url_list = CommonService.get_domain_name()
- try:
- headers = {
- 'Authorization': request.META.get('HTTP_AUTHORIZATION')
- }
- type_list = []
- type_count = 0
- for url in url_list:
- url = url + request.path.replace('global/', '')
- res = requests.get(url=url, params=request_dict, headers=headers)
- result = res.json()
- if result['result_code'] == 0:
- for item in result['result']['type']:
- flag = 0
- for each in type_list:
- if item['type'] == each['type']:
- each['count'] += item['count']
- type_count += item['count']
- flag = 1
- break
- if flag == 0:
- type_list.append(item)
- type_count += item['count']
- for item in type_list:
- item['rate'] = round(item['count'] / type_count * 100, 2)
- else:
- return response.json(result['result_code'])
- res = {
- 'type': CommonService.list_sort(type_list)
- }
- return response.json(0, res)
- except Exception as e:
- print(e)
- return response.json(500)
- @classmethod
- def global_regional(cls, request, request_dict, response):
- """
- 全球设备分布
- @param request:请求
- @param request_dict:请求参数
- @param response:响应对象
- @return:
- """
- url_list = CommonService.get_domain_name()
- try:
- headers = {
- 'Authorization': request.META.get('HTTP_AUTHORIZATION')
- }
- device_list = []
- device_count = 0
- region_list = []
- region_count = 0
- for url in url_list:
- url = url + request.path.replace('global/', '')
- res = requests.get(url=url, params=request_dict, headers=headers)
- result = res.json()
- if result['result_code'] == 0:
- # 处理地区
- for item in result['result']['countries']:
- flag = 0
- for each in device_list:
- if each['countryName'] == item['countryName']:
- each['count'] += int(item['count'])
- device_count += int(item['count'])
- flag = 1
- break
- if flag == 0:
- device_list.append(item)
- device_count += int(item['count'])
- for item in device_list:
- rate = round(item['count'] / device_count * 100, 2)
- item['rate'] = rate
- for item in result['result']['continent']:
- flag = 0
- for each in region_list:
- if each['continentName'] == item['continentName']:
- each['count'] += item['count']
- region_count += item['count']
- flag = 1
- break
- if flag == 0:
- region_list.append(item)
- region_count += item['count']
- for item in region_list:
- item['rate'] = round(item['count'] / region_count * 100, 2)
- else:
- return response.json(result['result_code'])
- res = {
- 'countries': CommonService.list_sort(device_list[:20]),
- 'continent': region_list
- }
- return response.json(0, res)
- except Exception as e:
- return response.json(500, repr(e))
- @classmethod
- def device_active(cls, request_dict, response):
- """
- 设备活跃数据
- @param request_dict:请求参数
- @request_dict starTime:开始时间
- @request_dict endTime:结束时间
- @param response:响应对象
- """
- start_time = request_dict.get('startTime', None) # 时间戳
- end_time = request_dict.get('endTime', None)
- unit_time = request_dict.get('timeUnit', None)
- if not all([start_time, end_time, unit_time]):
- return response.json(444, {'error param': 'startTime or endTime or timeUnit'})
- s_time = datetime.datetime.fromtimestamp(int(start_time))
- e_time = datetime.datetime.fromtimestamp(int(end_time))
- time_list = CommonService.cutting_time(s_time, e_time, unit_time)
- try:
- device_info_summary_qs = DeviceInfoSummary.objects.filter(
- time__range=(start_time, end_time), query_type=1).values('country', 'count')
- res = {}
- if not device_info_summary_qs.exists():
- return response.json(0, res)
- count_all = device_info_summary_qs.aggregate(total=Sum('count'))['total']
- video_list = []
- region_list = []
- for item in time_list:
- deivce_type_qs = device_info_summary_qs.filter(time__range=(item[0], item[1])).values('count')
- if deivce_type_qs.exists():
- count = deivce_type_qs.aggregate(total=Sum('count'))['total']
- else:
- count = deivce_type_qs.count()
- vod_dict = {
- 'count': count,
- 'rate': round(count / count_all * 100, 2),
- 'startTime': item[0],
- 'endTime': item[1]
- }
- video_list.append(vod_dict)
- res['vodHls'] = video_list
- for type_country in device_info_summary_qs:
- country_temp_dict = eval(type_country['country'])
- for k, v in country_temp_dict.items():
- flag = 0
- for each in region_list:
- if k == each['countryName']:
- each['count'] += v
- flag = 1
- break
- if flag == 0:
- region_list.append({
- 'countryName': k,
- 'count': v
- })
- for item in region_list:
- item['rate'] = round(item['count'] / count_all * 100, 2) if count_all else 0
- res['region'] = region_list
- return response.json(0, res)
- except Exception as e:
- print(e)
- return response.json(500)
- @classmethod
- def add_device(cls, request_dict, response):
- """
- 查询设备增长数据
- @param request_dict:请求参数
- @request_dict starTime:开始时间
- @request_dict endTime:结束时间
- @param response:响应对象
- """
- start_time = request_dict.get('startTime', None) # 时间戳
- end_time = request_dict.get('endTime', None)
- unit_time = request_dict.get('timeUnit', None)
- if not all([start_time, end_time, unit_time]):
- return response.json(444, {'error param': 'startTime or endTime or timeUnit'})
- try:
- uid_set_qs = DeviceInfoSummary.objects.filter(time__range=(start_time, end_time), query_type=0)
- res = {}
- if not uid_set_qs.exists():
- return response.json(0, res)
- count_all = uid_set_qs.aggregate(total=Sum('count'))['total']
- # 统计该时间段的设备数量(已去重)
- info_list = []
- region_list = []
- type_list = []
- version_list = []
- start_time = datetime.datetime.fromtimestamp(int(start_time))
- end_time = datetime.datetime.fromtimestamp(int(end_time))
- time_list = CommonService.cutting_time(start_time, end_time, unit_time)
- for item in time_list:
- device_uid_qs = uid_set_qs.filter(time__range=(item[0], item[1]), query_type=0)
- if device_uid_qs.exists():
- count = device_uid_qs.aggregate(total=Sum('count'))['total']
- else:
- count = device_uid_qs.count()
- rate = round(count / count_all * 100, 2)
- info_dict = {
- 'startTime': item[0],
- 'endTime': item[1],
- 'count': count,
- 'rate': rate
- }
- info_list.append(info_dict)
- res['addDevice'] = info_list
- # 统计地区设备数量
- device_info_country_qs = uid_set_qs.values('country')
- for item in device_info_country_qs:
- country_temp_dict = eval(item['country'])
- for x, y in country_temp_dict.items():
- flag = 0
- for each in region_list:
- if x == each['countryName']:
- each['count'] += y
- flag = 1
- break
- if flag == 0:
- region_list.append({
- 'countryName': x,
- 'count': y
- })
- for item in region_list:
- item['rate'] = round(item['count'] / count_all * 100, 2) if count_all else 0
- res['region'] = CommonService.list_sort(region_list)
- # 统计设备类型数量
- device_type_qs = uid_set_qs.values('device_type')
- for item in device_type_qs:
- country_temp_dict = eval(item['device_type'])
- for x, y in country_temp_dict.items():
- flag = 0
- for each in type_list:
- if x == each['type']:
- each['count'] += y
- flag = 1
- break
- if flag == 0:
- type_list.append({
- 'type': x,
- 'count': y
- })
- for item in type_list:
- item['rate'] = round(item['count'] / count_all * 100, 2) if count_all else 0
- res['type'] = CommonService.list_sort(type_list)
- # 云存版本数量
- cloud_type_qs = uid_set_qs.values('vod_service')
- for cloud_type in cloud_type_qs:
- country_temp_dict = eval(cloud_type['vod_service'])
- for x, y in country_temp_dict.items():
- flag = 0
- for each in version_list:
- if x == each['type']:
- each['count'] += y
- flag = 1
- break
- if flag == 0:
- version_list.append({
- 'type': x,
- 'count': y
- })
- for item in version_list:
- item['rate'] = round(item['count'] / count_all * 100, 2) if count_all else 0
- res['version'] = CommonService.list_sort(version_list)
- return response.json(0, res)
- except Exception as e:
- print(e)
- return response.json(500, repr(e))
- @classmethod
- def regional_statistics(cls, response):
- """
- 统计地区设备数量
- @param response:响应对象
- """
- all_device_qs = DeviceInfoSummary.objects.filter(query_type=0).values('continent', 'count', 'country')
- if not all_device_qs.exists():
- return response.json(173)
- country_count = all_device_qs.aggregate(total=Sum('count'))['total']
- res = {}
- try:
- continent_list = []
- region_list = []
- for item in all_device_qs:
- country_temp_dict = eval(item['country'])
- for x, y in country_temp_dict.items():
- flag = 0
- for each in region_list:
- if x == each['countryName']:
- each['count'] += y
- flag = 1
- break
- if flag == 0:
- region_list.append({
- 'countryName': x,
- 'count': y
- })
- for item in region_list:
- item['rate'] = round(item['count'] / country_count * 100, 2) if country_count else 0
- for item in all_device_qs:
- continent_temp_dict = eval(item['continent'])
- for x, y in continent_temp_dict.items():
- flag = 0
- for each in continent_list:
- if x == each['continentName']:
- each['count'] += y
- flag = 1
- break
- if flag == 0:
- continent_list.append({
- 'continentName': x,
- 'count': y
- })
- for item in continent_list:
- item['rate'] = round(item['count'] / country_count * 100, 2) if country_count else 0
- res['countries'] = CommonService.list_sort(region_list)
- res['continent'] = CommonService.list_sort(continent_list)
- return response.json(0, res)
- except Exception as e:
- print(e)
- return response.json(500)
- @classmethod
- def type_statistics(cls, response):
- """
- 统计设备类型
- @param response:响应对象
- @return:
- """
- all_device_qs = DeviceInfoSummary.objects.filter(query_type=0).values('device_type', 'count')
- if not all_device_qs.exists():
- return response.json(173)
- country_count = all_device_qs.aggregate(total=Sum('count'))['total']
- res = {}
- try:
- device_type_list = []
- for item in all_device_qs:
- country_temp_dict = eval(item['device_type'])
- for t, c in country_temp_dict.items():
- flag = 0
- for each in device_type_list:
- if t == each['type']:
- each['count'] += c
- flag = 1
- break
- if flag == 0:
- device_type_list.append({
- 'type': t,
- 'count': c
- })
- for item in device_type_list:
- item['rate'] = round(item['count'] / country_count * 100, 2) if country_count else 0
- res['type'] = CommonService.list_sort(device_type_list)
- return response.json(0, res)
- except Exception as e:
- print(e)
- return response.json(500)
|