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一起进步吧!!!

相关推荐
程序设计实验室21 小时前
当人人都能用 AI 写代码时,我为什么选择重回 Django?
django·djangostarter
zone773921 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant1 天前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来1 天前
在node项目中执行python脚本
前端·python·node.js
IVEN_1 天前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend1 天前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽1 天前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_2 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python