django缓存的使用

196 阅读1分钟
首先安装
pip install drf-extensions
在settings.py中配置
REST_FRAMEWORK_EXTENSIONS
REST_FRAMEWORK_EXTENSIONS = {
    'DEFAULT_OBJECT_CACHE_KEY_FUNC': 'rest_framework_extensions.utils.default_object_cache_key_func',
    'DEFAULT_LIST_CACHE_KEY_FUNC': 'rest_framework_extensions.utils.default_list_cache_key_func',
    'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 15  #过期时间定义时间 单位为秒
}
接口写法  在你的接口文件里
在类里加上即可
from rest_framework_extensions.cache.mixins import CacheResponseMixin
class Banners(CacheResponseMixin, View):
    def get(self, request, *args, **kwargs):
        authentication_classes = (JSONWebTokenAuthentication,)
        permission_classes = (IsAuthenticated,)
        if request.method == "GET":
            goods_list = Banner.objects.all()
            gd = BannerSerializer(instance=goods_list, many=True)
            if goods_list:
                response = {"code": "200", "data": gd.data}
                return JsonResponse(response, safe=False)
            else:
                response = {"code": "400", "data": gd.data}
                return JsonResponse(response, safe=False)