123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- # -*- encoding: utf-8 -*-
- """
- @File : UserDataController.py
- @Time : 2022/8/16 10:44
- @Author : peng
- @Email : zhangdongming@asj6.wecom.work
- @Software: PyCharm
- """
- import time
- import oss2
- from django.db import connection
- from django.db import transaction
- from django.db.models import Q, Count
- from django.views.generic.base import View
- import datetime
- from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
- from Controller.DeviceConfirmRegion import Device_Region
- from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
- iotdeviceInfoModel, UIDModel, Device_User, UserFamily, FamilyMember, FamilyMemberPermission, \
- FamilyRoomDevice, FamilyRoom, FamilyMemberJoin, GatewaySubDevice, CountryModel, DeviceTypeModel
- from Object.ResponseObject import ResponseObject
- from Object.TokenObject import TokenObject
- 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 = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
- lang = request_dict.get('lang', None)
- if lang:
- response = ResponseObject(lang)
- else:
- response = ResponseObject(token.lang) if token.lang else ResponseObject()
- if token.code != 0:
- return response.json(token.code)
- user_id = token.userID
- if operation == 'increase': # 查询新增用户数据
- return self.device_increase(request_dict, response)
- if operation == 'type': # 统计设备类型
- return self.type_statistics(response)
- if operation == 'regional': # 设备地区分布
- return self.regional_statistics(response)
- else:
- return response.json(414)
- @classmethod
- def regional_statistics(cls, response):
- """
- 统计地区设备数量
- @param response:响应对象
- """
- device_info_qs = Device_Info.objects.all()
- count = device_info_qs.count()
- device_info_qs = device_info_qs.values('userID__region_country').order_by('userID__region_country').distinct()
- if not device_info_qs.exists():
- return response.json(444)
- try:
- device_country_list = []
- for device_user in device_info_qs:
- country_id = device_user['userID__region_country']
- country_qs = CountryModel.objects.filter(id=country_id).values('country_name', 'id')
- countryName = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
- device_info = Device_Info.objects.filter(userID__region_country=country_id).values('id').count()
- rate = round(device_info / count * 100, 2)
- res = {
- 'id': country_id,
- 'name': countryName,
- 'total': device_info,
- 'rate': rate
- }
- device_country_list.append(res)
- return response.json(0, device_country_list)
- except Exception as e:
- print(e)
- return response.json(500)
- @classmethod
- def type_statistics(cls, response):
- """
- 统计设备类型
- @param response:响应对象
- @return:
- """
- device_info_qs = Device_Info.objects.filter().values('Type').order_by('Type').distinct()
- if not device_info_qs.exists():
- return response.json(444)
- device_type_list = []
- try:
- for device_info in device_info_qs:
- type = device_info['Type']
- device_type_qs = DeviceTypeModel.objects.filter(type=type).values('name')
- if not device_type_qs.exists():
- continue
- total = Device_Info.objects.filter(Type=type).count()
- res = {
- 'type': device_type_qs[0]['name'],
- 'total': total
- }
- device_type_list.append(res)
- return response.json(0, device_type_list)
- except Exception as e:
- print(e)
- return response.json(500)
- @classmethod
- def device_increase(cls, request_dict, response):
- """
- 查询用户增长数据
- @param request_dict:请求参数
- @request_dict startTime:开始时间
- @request_dict endTime:结束时间
- @param response:响应对象
- @return:
- """
- start_time = request_dict.get('startTime', None)
- end_time = request_dict.get('endTime', None)
- if not all([start_time, end_time]):
- return response.json(444, {'error param': 'startTime or endTime'})
- start_time = datetime.datetime.fromtimestamp(int(start_time))
- end_time = datetime.datetime.fromtimestamp(int(end_time))
- try:
- user_qs = Device_User.objects.filter(data_joined__range=(start_time, end_time))
- res = {
- 'total': user_qs.count(),
- 'region': []
- }
- if user_qs.exists():
- user_country_qs = user_qs.values('region_country').annotate(count=Count('region_country')).order_by(
- '-count')
- region = []
- for item in user_country_qs:
- country_id = item['region_country']
- country_qs = CountryModel.objects.filter(id=country_id).values('country_name')
- country_name = country_qs[0]['country_name'] if country_qs.exists() else '未知区域'
- country_dict = {
- 'countryName': country_name,
- 'count': item['count']
- }
- region.append(country_dict)
- res['region'] = region
- return response.json(0, res)
- except Exception as e:
- return response.json(500, repr(e))
|