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

相关推荐
zyk_computer1 分钟前
AI 时代,或许 Rust 比 Python 更合适
人工智能·后端·python·ai·rust·ai编程·vibe coding
weixin199701080163 分钟前
【保姆级教程】淘宝/天猫商品详情 API(item_get)接入指南:Python/Java/PHP 调用示例与 JSON 返回值解析
java·python·php
萌新小码农‍10 分钟前
python装饰器
开发语言·前端·python
KK溜了溜了13 分钟前
Python从入门到精通
服务器·开发语言·python
2401_8844541527 分钟前
mysql处理复杂SQL性能_InnoDB优化器与MyISAM差异
jvm·数据库·python
m0_470857641 小时前
golang如何实现目录大小统计_golang目录大小统计实现方案
jvm·数据库·python
消晨消晨1 小时前
MONAI初上手——模型构建
pytorch·python·monai
weixin_444012931 小时前
如何在多实例管理时隐藏MySQL版本信息_安全混淆与配置
jvm·数据库·python
weixin_459753941 小时前
SQL处理大规模分组聚合的内存限制_调整服务器配置
jvm·数据库·python
Rust语言中文社区2 小时前
【Rust日报】2026-05-14 Pyrefly v1.0 正式发布:快速的 Python 类型检查器和语言服务器
开发语言·后端·python·rust