import json
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from api.models import Rank
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import cache_page
from rest_framework.views import APIView
from django.utils.decorators import method_decorator
TIMEOUT = 86400
from django.core.cache import cache, caches
@method_decorator(decorator=csrf_protect, name='post')
class RankView(APIView):
def get(self, request, client_number):
if Rank.objects.filter(client_number=client_number):
if cache.get('data'):# 查询缓存中有没有存着数据
result = json.loads(cache.get('data'))
result[client_number] = result[str(client_number)]
print('缓存的')
else:
rank_obj = Rank.objects.order_by('-mark')
result = {'msg': '查询成功'}
order = 1
for rank in rank_obj:
result[rank.client_number] = {'mark': rank.mark, 'order': order}
order += 1
cache.set('data', json.dumps(result), TIMEOUT)# 将查出来的数据存到缓存中,getset只能获取和存储字符串
result[str(client_number)] = result[client_number]
print('生成的')
else:
result = {'msg': '没有相关数据'}
return Response(result)
def post(self, request):
try:
c_number = request.POST['client_number']
c_mark = request.POST['client_mark']
Rank.objects.update_or_create(
client_number=c_number,
defaults={'mark': c_mark}
)
result = {'msg': '上传成功'}
except:
result = {'msg': '上传失败'}
cache.delete('data') # 将缓存中的旧数据删掉
return JsonResponse(result)