• django实现消除缓存


    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)
    
    
    
    
  • 相关阅读:
    2014-11-24 作业
    数据库查询基本部分
    SQL备份还原,分离附加
    SQL基础2
    SQL基础,与数据类型;
    if语句解一元二次方程~
    用C语言计算圆的面积~!!!!!!!
    C语言基础
    数据导出和TreeView
    MDI窗体容器和权限设置
  • 原文地址:https://www.cnblogs.com/python001-vip/p/12676407.html
Copyright © 2020-2023  润新知