django接口缓存
接口缓存
- 以轮播图接口为例
- APIResponse 见 https://www.cnblogs.com/unrealqcc/p/18194581 封装Response
普通缓存
common_mixin.py
from rest_framework.mixins import ListModelMixin
from .common_logger import logger
from utils.common_response import APIResponse
from django.core.cache import cache
class APIListModelMixin(ListModelMixin):
cache_key = None
def list(self, request, *args, **kwargs):
assert self.cache_key, '必须设置cache_key'
data_list = cache.get(self.cache_key)
if not data_list:
logger.info('走数据库')
data_list = super().list(request, *args, **kwargs).data
cache.set(self.cache_key, data_list)
return APIResponse(results=data_list)
views.py
from rest_framework.viewsets import GenericViewSet
from utils.common_mixin import APIListModelMixin
from .models import Banner
from .serializer import Bannerserializer
class BannerView(GenericViewSet,APIListModelMixin):
queryset = Banner.objects.all()
serializer_class = Bannerserializer
cache_key = 'banner_list'
缓存装饰器
common_mixin.py
from .common_logger import logger
from utils.common_response import APIResponse
from django.core.cache import cache
def redis_cache(cache_key):
def decorator(view_func):
def wrapper(self, request, *args, **kwargs):
data = cache.get(cache_key)
if data is None:
response = view_func(self, request, *args, **kwargs)
data = response.data
cache.set(cache_key, data)
else:
logger.info('使用缓存')
response = APIResponse(results=data)
return response
return wrapper
return decorator
views.py
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from utils.common_mixin import redis_cache
from utils.common_response import APIResponse
from .models import Banner
from .serializer import Bannerserializer
class BannerView(GenericViewSet,ListModelMixin):
queryset = Banner.objects.all()
serializer_class = Bannerserializer
@redis_cache(cache_key='banner_list')
def list(self, request, *args, **kwargs):
data_list =super().list(request, *args, **kwargs).data
return APIResponse(results=data_list)