From 8663ae502235d5253aaadeee6614b77fb728c94b Mon Sep 17 00:00:00 2001 From: xianfuxing Date: Wed, 27 May 2020 17:59:39 +0800 Subject: [PATCH] =?UTF-8?q?#=20=E6=94=B9=E4=B8=BA=E6=9C=AC=E6=9C=88?= =?UTF-8?q?=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/counter/api/views.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/apps/counter/api/views.py b/apps/counter/api/views.py index 300226f..2ffc3f9 100644 --- a/apps/counter/api/views.py +++ b/apps/counter/api/views.py @@ -87,12 +87,30 @@ class DeviceLogStatisticAPIView(APIView, RoleMixin): else: total_count = 0 + tz = pytz.timezone("UTC") + today = datetime.now(tz).date() + + # calc monthly count, put it in redis as cache. + if cache.has_key('monthly_count'): + monthly_count = cache.get('monthly_count') + else: + cur_month = tz.localize(datetime.combine(datetime(today.year, today.month, 1), time(0, 0)), is_dst=None) + one_month_ago_queryset = [ + DeviceCount.objects.filter(device_id=x['device_id'], data_time=x['max_time']).order_by('-count')[0] + for x in DeviceCount.objects.filter( + data_time__lt=cur_month, device_id__in=devices).values('device_id').annotate( + max_time=Max('data_time'))] + if one_month_ago_queryset: + one_month_ago_count = sum(map(lambda x: int(x.count), one_month_ago_queryset)) + monthly_count = total_count - one_month_ago_count + else: + monthly_count = 0 + cache.set('monthly_count', monthly_count, 60 * 60) + # calc daily count, put it in redis as cache. if cache.has_key('daily_count'): daily_count = cache.get('daily_count') else: - tz = pytz.timezone("UTC") - today = datetime.now(tz).date() midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None) one_day_ago_queryset = [DeviceCount.objects.filter(device_id=x['device_id'], data_time=x['max_time']).order_by('-count')[0] for x in DeviceCount.objects.filter( @@ -103,7 +121,8 @@ class DeviceLogStatisticAPIView(APIView, RoleMixin): else: daily_count = 0 cache.set('daily_count', daily_count, 60 * 60) - data = {'total_count': total_count, 'daily_count': daily_count} + + data = {'total_count': total_count - monthly_count, 'daily_count': daily_count} return Response(data) def get_devices(self):