Django REST framework 实现缓存机制以优化性能

Django REST framework 实现缓存机制以优化性能

页面首页中,导航菜单或轮播广告在项目中每一个页面都会被用户频繁访问到,所以我们可以实现缓存,减少MySQL数据库的查询压力,使用内存缓存可以加快数据查询速度。

cache_page 装饰器

根据django官方文档,

试图缓存:https://docs.djangoproject.com/zh-hans/5.0/topics/cache/#the-per-view-cache

示例:

使用缓存框架的通用办法是缓存视图结果。django.views.decorators.cache 定义了一个 cache_page 装饰器,它将自动缓存视图的响应:

python 复制代码
from django.views.decorators.cache import cache_page


@cache_page(60 * 15)
def my_view(request): ...

method_decorator@ 装饰器

装饰类视图:https://docs.djangoproject.com/zh-hans/3.2/topics/class-based-views/intro/#decorating-the-class

  • @ 装饰器语法(直接装饰器)

    1. 直接应用:装饰器直接应用于函数或方法的定义上。
    2. 作用域:装饰器的作用域仅限于被装饰的函数或方法。
    3. 继承性:如果一个方法被装饰,那么它的直接子类继承该方法时,不会自动继承装饰器。子类需要显式地添加相同的装饰器。
    4. 可读性:代码更直观,因为装饰器直接位于方法定义之前,易于理解和追踪。
    5. 限制:如果需要在继承链中多个级别应用相同的装饰器,需要在每个类中重复相同的装饰器代码。
  • method_decorator(类级别装饰器)

    1. 动态应用:装饰器在类定义之后、方法定义之前动态应用。
    2. 作用域:可以为类中的一个或多个方法添加装饰器。
    3. 继承性:通过 method_decorator 应用的装饰器会被所有继承该类的子类继承,无需在子类中重复添加。
    4. 灵活性:可以在不修改原始方法定义的情况下,为类的方法添加装饰器。
    5. 复杂性:可能稍微降低代码的可读性,因为装饰器的应用与方法定义分离。

代码实现

前提是的settings中配置好了CACHE

python 复制代码
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.generics import ListAPIView
import constants

class CacheListAPIView(ListAPIView):
    """列表缓存视图"""
    @method_decorator(cache_page(time_out=constants.LIST_PAGE_CACHE_TIME))
    def get(self,request, *args, **kwargs):
        # 重写ListAPIView的get方法,但是不改动源代码。仅仅装饰而已
        return super().get(request, *args, **kwargs)

此时,主页视图中的头部脚部轮播图等api接口都可以继承该类,实现缓存

python 复制代码
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

此时,访问试图后,缓存数据库中就有缓存好的信息了。

若有错误与不足请指出,关注DPT一起进步吧!!!

相关推荐
星云穿梭17 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵18 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠1 天前
大模型之LangGraph技术体系
python·llm
hboot2 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔3 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试