缓存导航与轮播图数据
导航菜单在项目中每一个页面都会被用户访问到,
轮播广告置于首页,也是每一个用户最先看到的。
对这两个功能的数据库获取,会发生很多次,
但这两个功能的数据又不经常发生变动。
所以我们使用缓存,减少MySQL数据库的查询压力,
同时,使用内存缓存也加快数据查询速度。
django提供的缓存装饰器是用于函数(方法)的。
视图缓存:https://docs.djangoproject.com/zh-hans/3.2/topics/cache/#the-per-view-cache
装饰类视图:https://docs.djangoproject.com/zh-hans/3.2/topics/class-based-views/intro/#decorating-the-class
我们可以在utils文件夹中,创建一个 views.py
,
在其中创建一个被缓存装饰器装饰的类,以后,哪个类需要使用到缓存,只要继承于这个类就可以。
utils/views.py,代码:
import constants
from rest_framework.generics import ListAPIView
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
class CacheListAPIView(ListAPIView):
"""列表缓存视图"""
@method_decorator(cache_page(constants.LIST_PAGE_CACHE_TIME))
def get(self,request, *args, **kwargs):
# 重写ListAPIView的get方法,但是不改动源代码。仅仅装饰而已
return super().get(request, *args, **kwargs)
utils/constants.py,代码:
# 列表页数据的缓存周期,单位:秒
LIST_PAGE_CACHE_TIME = 24 * 60 * 60
home/views.py,代码:
import constants
from views import CacheListAPIView
from .models import Nav, Banner
from .serializers import NavModelSerializer, BannerModelSerializer
class NavHeaderListAPIView(CacheListAPIView):
"""顶部导航视图"""
queryset = Nav.objects.filter(position=constants.NAV_HEADER_POSITION, is_show=True, is_deleted=False).order_by("orders", "-id")[:constants.NAV_HEADER_SIZE]
serializer_class = NavModelSerializer
class NavFooterListAPIView(CacheListAPIView):
"""脚部导航视图"""
queryset = Nav.objects.filter(position=constants.NAV_FOOTER_POSITION, is_show=True, is_deleted=False).order_by("orders", "-id")[:constants.NAV_FOOTER_SIZE]
serializer_class = NavModelSerializer
class BannerListAPIView(CacheListAPIView):
"""轮播广告视图"""
queryset = Banner.objects.filter(is_show=True, is_deleted=False).order_by("orders", "-id")[:constants.BANNER_SIZE]
serializer_class = BannerModelSerializer
由于我们前面设置了redis缓存,
所以缓存的数据会被放到redis中。