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

相关推荐
大模型真好玩16 分钟前
准确率飙升!GraphRAG如何利用知识图谱提升RAG答案质量(额外篇)——大规模文本数据下GraphRAG实战
人工智能·python·mcp
198917 分钟前
【零基础学AI】第30讲:生成对抗网络(GAN)实战 - 手写数字生成
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·近邻算法
applebomb26 分钟前
没合适的组合wheel包,就自行编译flash_attn吧
python·ubuntu·attention·flash
Chasing__Dreams1 小时前
python--杂识--18.1--pandas数据插入sqlite并进行查询
python·sqlite·pandas
彭泽布衣2 小时前
python2.7/lib-dynload/_ssl.so: undefined symbol: sk_pop_free
python·sk_pop_free
喜欢吃豆2 小时前
从零构建MCP服务器:FastMCP实战指南
运维·服务器·人工智能·python·大模型·mcp
草履虫建模3 小时前
Redis:高性能内存数据库与缓存利器
java·数据库·spring boot·redis·分布式·mysql·缓存
一个处女座的测试3 小时前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
nananaij3 小时前
【Python基础入门 re模块实现正则表达式操作】
开发语言·python·正则表达式
蛋仔聊测试3 小时前
Playwright 网络流量监控与修改指南
python