Forráskód Böngészése

用户使用app频率统计

tanghongbin 5 éve
szülő
commit
07f84ba310
4 módosított fájl, 258 hozzáadás és 5 törlés
  1. 5 1
      Ansjer/urls.py
  2. 91 3
      Controller/AdminManage.py
  3. 137 0
      Controller/StatisticsController.py
  4. 25 1
      Model/models.py

+ 5 - 1
Ansjer/urls.py

@@ -9,7 +9,8 @@ from Controller import FeedBack, EquipmentOTA, EquipmentInfo, AdminManage, AppIn
     UserController, CloudVod, OrderContrller, VodBucket, DetectController, DeviceShare, UserBrandController, \
     StsOssController, UIDPreview, OssCrd, SysMsg, UidUser, EquipmentManagerV2, EquipmentManagerV3, PushDeploy, \
     AppSetController, \
-    ApplicationController, UserExController, CloudStorage, TestApi, UserBrandControllerV2
+    ApplicationController, UserExController, CloudStorage, TestApi, UserBrandControllerV2, GenerateDataController, \
+    StatisticsController
 
 urlpatterns = [
     url(r'^testApi/(?P<operation>.*)$', TestApi.testView.as_view()),
@@ -206,6 +207,9 @@ urlpatterns = [
     url(r'^equipment/flow_test$', EquipmentManager.uid_status_test),
     url(r'^account/appFrequency/(?P<operation>.*)$', UserController.UserAppFrequencyView.as_view()),
     url(r'^v2/userbrand/(?P<operation>.*)$', UserBrandControllerV2.UserBrandV2.as_view()),
+    url(r'^test/add$', GenerateDataController.GenerateDataView.as_view()),
+    url(r'^statistcs/appFrequencyMonth$', StatisticsController.statistcsAppFrequency),
+    url(r'^statistcs/appFrequencyYear$', StatisticsController.statistcsAppFrequencyYear),
     # app 设备消息模板
     # 路由加参数参考
     # url(r'^(?P<path>.*)/(?P<UID>.*)/lls$', Test.Test.as_view(), name=u'gg'),

+ 91 - 3
Controller/AdminManage.py

@@ -1,10 +1,13 @@
 # -*- coding: utf-8 -*-
-from django.db.models import Count
+import time
+
+from django.db.models import Count,Q
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic import TemplateView
 from django.utils.decorators import method_decorator
 from django.contrib.auth.hashers import make_password  # 对密码加密模块
-from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel
+from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel, UserAppFrequencyModel, \
+    AppFrequencyStatisticsModel, AppFrequencyYearStatisticsModel
 from Service.ModelService import ModelService
 from django.utils import timezone
 from Model.models import Access_Log, Device_User
@@ -71,6 +74,10 @@ class AdminManage(TemplateView):
             return self.getAreaDeviceType(userID, response)
         if operation == 'getDeviceType':
             return self.getDeviceType(userID, response)
+        if operation == 'getAppFrequency':
+            return self.getAppFrequency(userID, request_dict, response)
+        if operation == 'getHistoryAppFrequency':
+            return self.getAllAppFrequency(userID, response)
 
     def resetUserPwd(self, request_dict, userID, response):
         own_permission = ModelService.check_perm(userID=userID, permID=50)
@@ -335,9 +342,89 @@ class AdminManage(TemplateView):
             data.append(us)
             quantity += us['quantity']
         model_data['quantity'] = quantity
-
         return response.json(0, res)
 
+    def getAppFrequency(self, userID, request_dict, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+
+        # 当前的年份
+        current_time = int(time.time())
+        localtime = time.localtime(current_time)
+        current_year = localtime.tm_year
+        current_month = localtime.tm_mon
+
+        start_year = end_year = current_year
+        end_month = current_month
+        start_month = 1
+
+        result = []
+        if end_month != 12:
+            start_month = end_month + 1
+            start_year = current_year - 1
+
+        time_struct = [start_year, start_month, 0, 0, 0, 0, 0, 0, 0]
+        key_formal = '{year}{month}'
+        for i in range(12):
+            result.append({
+                'date_time': key_formal.format(year=time_struct[0], month=str(time_struct[1]).zfill(2)),
+                'data': None
+            })
+
+            month = time_struct[1] + 1
+            if month > 12:
+                time_struct[0] = time_struct[0] + 1
+                time_struct[1] = 1
+            else:
+                time_struct[1] = month
+        #
+        afs_qs = {}
+        if start_year == end_year:
+            afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month, month__lte=end_month).values().order_by('-year', 'month'))
+        else:
+            afs_qs = list(AppFrequencyStatisticsModel.objects.filter(year=start_year, month__gte=start_month).values().order_by('-year', 'month'))
+            tmps_qs = list(AppFrequencyStatisticsModel.objects.filter(year=end_year, month__lte=end_month).values().order_by('-year', 'month'))
+            for tmp in tmps_qs:
+                afs_qs.append(tmp)
+
+        tmp_dict = {}
+
+        for afs in afs_qs:
+            key = key_formal.format(year=afs['year'], month=str(afs['month']).zfill(2))
+            tmp_dict[key] = json.loads(afs['data'])
+
+        for res in result:
+            if tmp_dict.__contains__(res['date_time']):
+                res['data'] = tmp_dict[res['date_time']]
+        print(result)
+
+        return response.json(0, result)
+
+    def getAllAppFrequency(self, userID, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+
+        # 取出请求年份的统计好的数据
+        print('start')
+        time_struct = time.localtime()
+        current_year = time_struct.tm_year
+        start_year = current_year - 5 + 1
+        afs_qs = AppFrequencyYearStatisticsModel.objects.filter(year__gte=start_year, year__lt=current_year).order_by(
+            '-year')
+        if afs_qs.exists():
+            afs_qs = afs_qs.values('id', 'data', 'num', 'year')
+            res = []
+            for afs in afs_qs:
+                res.append({
+                    'year': afs['year'],
+                    'data': json.loads(afs['data'])
+                })
+            return response.json(0, res)
+        else:
+            return response.json(0, [])
+
 
 @require_http_methods(["GET"])
 def getUserIds(request):
@@ -424,3 +511,4 @@ def search_user_by_content(request):
         sqlDict['count'] = count
         return response.json(0, sqlDict)
     return response.json(0, {'datas': [], 'count': 0})
+

+ 137 - 0
Controller/StatisticsController.py

@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+import time
+
+from django.db.models import Count
+from django.views.decorators.csrf import csrf_exempt
+
+from Model.models import UserAppFrequencyModel, AppFrequencyStatisticsModel, Device_User, \
+    AppFrequencyYearStatisticsModel
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+
+
+@csrf_exempt
+def statistcsAppFrequency(request):
+    request.encoding = 'utf-8'
+    response = ResponseObject()
+    if request.method == 'POST':
+        request_dict = request.POST
+    elif request.method == 'GET':
+        request_dict = request.GET
+    else:
+        return response.json(444)
+
+    token = TokenObject(request_dict.get('token', None))
+    if token.code != 0:
+        return response.json(token.code)
+
+    target_year = request_dict.get('year', None)
+    target_month = request_dict.get('month', None)
+
+    localtime = time.localtime()
+    current_month = localtime.tm_mon
+    current_year = localtime.tm_year
+
+    if target_year and target_month:
+        current_year = int(target_year)
+        current_month = int(target_month)
+
+    time_struct = [current_year, 1, 1, 0, 0, 0, 0, 0, 0]
+
+    # 该月的开始时间
+    time_struct[1] = current_month
+    start_time = time.mktime(tuple(time_struct))
+
+    # 该月的结束时间
+    time_struct[1] = current_month + 1
+    end_time = time.mktime(tuple(time_struct))
+
+    # 统计该月的数据
+    uaf_qs = UserAppFrequencyModel.objects.filter(data_time__gte=start_time, data_time__lt=end_time) \
+        .values('type').annotate(quantity=Count('id')).order_by()
+
+    afs_qs = AppFrequencyStatisticsModel.objects.filter(year=current_year, month=current_month)
+
+    if afs_qs.exists():
+        afs_qs.update(data=json.dumps(uaf_qs))
+    else:
+        data = {
+            'data': json.dumps(list(uaf_qs)),
+            'month': current_month,
+            'year': current_year
+        }
+        AppFrequencyStatisticsModel.objects.create(**data)
+    return response.json(0)
+
+
+@csrf_exempt
+def statistcsAppFrequencyYear(request):
+    request.encoding = 'utf-8'
+    response = ResponseObject()
+    if request.method == 'POST':
+        request_dict = request.POST
+    elif request.method == 'GET':
+        request_dict = request.GET
+    else:
+        return response.json(444)
+
+    token = TokenObject(request_dict.get('token', None))
+    if token.code != 0:
+        return response.json(token.code)
+
+    year = request_dict.get('year', None)
+
+    localtime = time.localtime()
+
+    current_year = localtime.tm_year
+    if year:
+        current_year = int(year)
+
+    afs_qs = AppFrequencyStatisticsModel.objects.filter(year=current_year).values('data', 'month')
+    # num = Device_User.objects.count()
+    num = 300000
+
+    res = []
+    result = {
+        0: 0,
+        1: 0,
+        2: 0,
+        3: 0,
+        4: 0,
+        5: 0,
+        6: 0
+    }
+    quantity = 0
+    for afs in afs_qs:
+        data = json.loads(afs['data'])
+        for item in data:
+            result[item['type']] += item['quantity']
+            quantity += item['quantity']
+
+    tmps = []
+    for k, v in result.items():
+        tmp = {
+            'type': k,
+            'value': round(v / 12 / num, 3)
+        }
+        tmps.append(tmp)
+    res.append({
+        'year': current_year,
+        'data': tmps
+    })
+    print(res)
+
+    afys_qs = AppFrequencyYearStatisticsModel.objects.filter(year=current_year)
+    #
+    if afys_qs.exists():
+        afys_qs.update(data=json.dumps(res))
+    else:
+        data = {
+            'data': json.dumps(res),
+            'year': current_year,
+            'num': num
+        }
+        AppFrequencyYearStatisticsModel.objects.create(**data)
+    return response.json(0)

+ 25 - 1
Model/models.py

@@ -922,4 +922,28 @@ class UserAppFrequencyModel(models.Model):
         verbose_name = '用户使用APP频率表'
         verbose_name_plural = verbose_name
         db_table = 'user_app_frequency'
-        ordering = ('-add_time',)
+        ordering = ('-add_time',)
+
+
+class AppFrequencyStatisticsModel(models.Model):
+    id = models.AutoField(primary_key=True)
+    data = models.TextField(default='', verbose_name='统计好的数据')
+    month = models.IntegerField(default=0, verbose_name='月份')
+    year = models.IntegerField(default=0, verbose_name='年份')
+
+    class Meta:
+        verbose_name = 'app月使用频率统计表'
+        verbose_name_plural = verbose_name
+        db_table = 'app_frequency_statistics'
+
+
+class AppFrequencyYearStatisticsModel(models.Model):
+    id = models.AutoField(primary_key=True)
+    data = models.TextField(default='', verbose_name='统计好的数据')
+    year = models.IntegerField(default=0, verbose_name='年份')
+    num = models.IntegerField(default=0, verbose_name='总人数')
+
+    class Meta:
+        verbose_name = 'app使用频率统计表,年度统计'
+        verbose_name_plural = verbose_name
+        db_table = 'app_frequency_year_statistics'