Procházet zdrojové kódy

根据设备类型查询活跃用户

peng před 11 měsíci
rodič
revize
d28ae3a1d5

+ 52 - 1
AdminController/dataSystemManagement/UserDataController.py

@@ -37,6 +37,8 @@ class UserDataView(View):
             return self.user_increase(request_dict, response)
         elif operation == 'active':  # 查询用户活跃数据
             return self.user_active(request_dict, response)
+        elif operation == 'active_user':  # 查询用户活跃数据
+            return self.get_active_user(request_dict, response)
         elif operation == 'region':  # 查询用户地区分布
             return self.user_region(response)
         elif operation == 'global/increase':  # 查询全球用户新增数据
@@ -397,4 +399,53 @@ class UserDataView(View):
             }
             return response.json(0, res)
         except Exception as e:
-            return response.json(500, repr(e))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    @classmethod
+    def get_active_user(cls, request_dict, response):
+        """
+        查询用户活跃数据
+        @param request_dict:请求参数
+        @request_dict startTime:开始时间
+        @request_dict endTime:结束时间
+        @request_dict timeUnit:时间单位
+        @param response:响应对象
+        @return:
+        """
+        start_time = request_dict.get('startTime', None)
+        end_time = request_dict.get('endTime', None)
+        device_type = request_dict.get('device_type', None)
+        ucode = request_dict.get('ucode', None)
+        if not all([start_time, end_time]):
+            return response.json(444, {'error param': 'startTime or endTime'})
+        try:
+            all_user_qs = DeviceUserSummary.objects.filter(time__gte=start_time, time__lt=end_time,
+                                                           query_type=1).values('device_type', 'ucode')
+            # 处理用户地区
+            device_type_dict = {}
+            ucode_dict = {}
+            for item in all_user_qs:
+                if item['device_type']:
+                    for k, v in item['device_type'].items():
+                        if k in device_type_dict:
+                            device_type_dict[k] += v
+                        else:
+                            device_type_dict[k] = v
+                if item['ucode']:
+                    for k, v in item['ucode'].items():
+                        if k in ucode_dict:
+                            ucode_dict[k] += v
+                        else:
+                            ucode_dict[k] = v
+            res = {
+                'device_type': device_type_dict,
+                'ucode': ucode_dict
+            }
+            if device_type:
+                res['device_type'] = {device_type: device_type_dict.get(device_type, 0)}
+            if ucode:
+                res['ucode'] = {ucode: ucode_dict.get(ucode, 0)}
+
+            return response.json(0, res)
+        except Exception as e:
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

+ 56 - 0
Controller/Cron/CronTaskController.py

@@ -784,6 +784,8 @@ class CronCollectDataView(View):
             return self.collect_play_back(response)
         elif operation == 'collectDeviceUser':  # 定时保存用户数据
             return self.collect_device_user(response)
+        elif operation == 'collectActivityUser':  # 定时保存用户数据
+            return self.collect_activity_user(response)
         elif operation == 'collectOrder':  # 定时保存订单数据
             return self.collect_order(response)
         elif operation == 'collectDeviceInfo':  # 定时保存设备数据
@@ -1447,6 +1449,60 @@ class CronCollectDataView(View):
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
     @staticmethod
+    def collect_activity_user(response):
+        try:
+            created_time = int(time.time())
+            today = datetime.datetime.today()
+            start_time = datetime.datetime(today.year, today.month, today.day)
+            end_time = start_time + datetime.timedelta(days=1)
+            start_time = CommonService.str_to_timestamp(start_time.strftime('%Y-%m-%d %H:%M:%S'))
+            end_time = CommonService.str_to_timestamp(end_time.strftime('%Y-%m-%d %H:%M:%S'))
+            thread = threading.Thread(target=CronCollectDataView.thread_collect_activity_user,
+                                      args=(start_time, end_time, created_time))
+            thread.start()  # 启动线程
+            return response.json(0)
+        except Exception as e:
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    @staticmethod
+    def thread_collect_activity_user(start_time, end_time, created_time):
+        try:
+            active_uid = UserExModel.objects.filter(updTime__gte=start_time, updTime__lt=end_time).values_list(
+                'userID__device_info__UID', flat=True).distinct()
+            active_device_qs = UidSetModel.objects.filter(uid__in=active_uid).values('addTime', 'device_type', 'ucode')
+            # 设备类型数据
+            device_type_qs = DeviceTypeModel.objects.values('name', 'type')
+            device_type_dict = {}
+            for item in device_type_qs:
+                device_type_dict[item['type']] = item['name']
+            with transaction.atomic():
+                if active_device_qs.exists():
+                    # 按设备设备类型
+                    active_device_type_list = active_device_qs.values('device_type').annotate(
+                        count=Count('device_type')).order_by('count')
+                    active_device_type_dict = {}
+                    for item in active_device_type_list:
+                        type_name = device_type_dict.get(item['device_type'], '未知设备类型')
+                        active_device_type_dict[type_name] = item['count']
+                    # 按ucode分类
+                    active_ucode_list = active_device_qs.values('ucode').annotate(count=Count('ucode')).order_by('count')
+                    active_ucode_dict = {}
+                    for item in active_ucode_list:
+                        ucode = item['ucode']
+                        if item['ucode'] == '':
+                            ucode = '未知ucode'
+                        active_ucode_dict[ucode] = item['count']
+                    user_qs = DeviceUserSummary.objects.filter(time=start_time)
+                    if user_qs.exists():
+                        user_qs.update(device_type=active_device_type_dict, ucode=active_ucode_dict)
+                    else:
+                        DeviceUserSummary.objects.create(time=start_time, query_type=1, created_time=created_time,
+                                                         device_type=active_device_type_dict, ucode=active_ucode_dict)
+        except Exception as e:
+            LOGGER.info(
+                'thread_collect_activity_user接口异常:errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno,
+                                                                                      repr(e)))
+    @staticmethod
     def collect_flow_info(response):
         try:
             unicom_qs = UnicomDeviceInfo.objects.filter(card_type=0).values('iccid').distinct().order_by('iccid')