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

相关推荐
985小水博一枚呀7 分钟前
【梯度消失|梯度爆炸】Vanishing Gradient|Exploding Gradient——为什么我的卷积神经网络会不好呢?
人工智能·python·深度学习·神经网络·计算机视觉·cnn·numpy
全能全知者1 小时前
不废话简单易懂的Selenium 页面操作与切换
python·selenium·测试工具·网络爬虫
你可以自己看3 小时前
python的基础语法
开发语言·python
akhfuiigabv4 小时前
使用Neo4j-Cypher-FT实现自然语言查询图数据库
数据库·python·oracle·neo4j
繁依Fanyi5 小时前
828华为云征文|华为Flexus云服务器搭建OnlyOffice私有化在线办公套件
服务器·开发语言·前端·python·算法·华为·华为云
zhangfeng11335 小时前
在 PyTorch 中,除了 pad_sequence 还有哪些其他处理序列数据的函数?时间序列数据 预处理
人工智能·pytorch·python·深度学习
python1565 小时前
Python Numpy布尔数组在数据分析中的应用
python·数据分析·numpy
木木ainiks5 小时前
django自用教程
数据库·django·sqlite
AIAdvocate5 小时前
力扣-96.不同的二叉搜索树 题目详解
python·算法·动态规划
luthane5 小时前
python 实现entropy熵算法
python·算法·概率论