# 优化统计接口性能
This commit is contained in:
parent
f8945b4d78
commit
791a753162
|
@ -97,6 +97,17 @@ class LatestStatisticAPIView(APIView, RoleMixin):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated]
|
||||||
|
|
||||||
def get(self, request, *args, **kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
|
username = request.user.username
|
||||||
|
cur_month_count_key = 'cur_month_count_{}'.format(username)
|
||||||
|
daily_count_key = 'daily_count_{}'.format(username)
|
||||||
|
cur_month_count = cache.get(cur_month_count_key)
|
||||||
|
daily_count = cache.get(daily_count_key)
|
||||||
|
|
||||||
|
if cur_month_count and daily_count:
|
||||||
|
data = {'cur_month_count': cur_month_count, 'daily_count': daily_count}
|
||||||
|
return Response(data)
|
||||||
|
|
||||||
|
# no cache
|
||||||
devices = self.get_devices()
|
devices = self.get_devices()
|
||||||
total_count_queryset = [DeviceCount.objects.filter(device_id=x['device_id'],
|
total_count_queryset = [DeviceCount.objects.filter(device_id=x['device_id'],
|
||||||
data_time=x['max_time']).order_by('-count')[0]
|
data_time=x['max_time']).order_by('-count')[0]
|
||||||
|
@ -122,6 +133,8 @@ class LatestStatisticAPIView(APIView, RoleMixin):
|
||||||
else:
|
else:
|
||||||
cur_month_count = total_count
|
cur_month_count = total_count
|
||||||
|
|
||||||
|
# set month cache
|
||||||
|
cache.set(cur_month_count_key, cur_month_count, 60 * 10)
|
||||||
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
|
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]
|
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(
|
for x in DeviceCount.objects.filter(
|
||||||
|
@ -132,6 +145,9 @@ class LatestStatisticAPIView(APIView, RoleMixin):
|
||||||
else:
|
else:
|
||||||
daily_count = 0
|
daily_count = 0
|
||||||
|
|
||||||
|
# set daily cache
|
||||||
|
cache.set(daily_count_key, daily_count, 60 * 10)
|
||||||
|
|
||||||
data = {'cur_month_count': cur_month_count, 'daily_count': daily_count}
|
data = {'cur_month_count': cur_month_count, 'daily_count': daily_count}
|
||||||
return Response(data)
|
return Response(data)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue