zoukankan      html  css  js  c++  java
  • django Rest Framework---缓存通过drf-extensions扩展来实现

    什么情况下使用缓存

    1.不经常更新的数据

    2.用户经常访问的一些页面,比如商品列表页、商品详情页等

    3.用户经常修改的一些操作:购物车、订单中心等

    关于DRF缓存扩展可以参考文档:http://chibisov.github.io/drf-extensions/docs/#caching

    安装

    pip install drf-extensions

    使用方法

    1.使用装饰器进行特定缓存

    可以使用@cache_response对视图类的方法进行特定缓存

    class CityView(views.APIView):
        @cache_response(60 * 15,cache ='special_cache'def get(self,request,* args,** kwargs):
            ...

    cache_response装饰器可以接收两个参数:

    1. timeout:缓存时间
    2. cache:缓存配置。默认是django的缓存,使用memcache

    如果不提供参数的话,也可以在settings中配置公共的缓存配置:

    # DRF扩展
    REST_FRAMEWORK_EXTENSIONS = {
        # 缓存时间
        'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 60,
        # 缓存存储
        'DEFAULT_USE_CACHE': 'default',
    }

    2.使用drf-extensions提供的扩展类

    drf-extensions扩展对于缓存提供了三个扩展类:

    • ListCacheResponseMixin : 提供了缓存返回列表数据的视图,本质是为 mixins.ListModelMixin 的list()添加了cache_response装饰器; get/。
    • RetrieveCacheResponseMixin:用于返回单一数据的是图,本质是为 mixins.RetrieveModelMixin 添加了cache_response装饰器;get/1/。
    • CacheResponseMixin:提供了List和Retrieve两种缓存,与ListModelMixin和RetrieveModelMixin一起配合使用。
    from rest_framework_extensions.cache.mixins import CacheResponseMixin
    
    
    class UserViewSet(CacheResponseMixin,viewsets.ModelViewSet):
        serializer_class = UserSerializer
        ....

    将缓存保存在redis中

    django默认的缓存是memcache,memcache将缓存放在内存中,不支持持久化,意味着我们重启之后,缓存就丢失了。

    drf-extensions默认使用的是django的缓存配置。我们还可以将缓存保存到redis中。

    安装django-redis

    pip install django-redis

    简体中文版django-redis文档:http://django-redis-chs.readthedocs.io/zh_CN/latest/

    作为 cache backend 使用配置

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379/",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "CONNECTION_POOL_KWARGS": {"max_connections": 100} # 配置连接池
            }
        }
    }
  • 相关阅读:
    五条面试忠告
    NET平台微服务
    CentOS,net core2 sdk nginx、supervisor、mysql
    搭建基于java环境
    产生唯一随机码的方法分析
    SpringBoot JPA 专题
    关于 MySQL 的 boolean 和 tinyint(1)
    org.springframework.data.mapping.PropertyReferenceException: No property created found for type
    交流心得
    github如何删除一个repository(仓库)
  • 原文地址:https://www.cnblogs.com/weihengblog/p/9478359.html
Copyright © 2011-2022 走看看