十、DRF缓存使用

使用时机:

经常被用户查询使用的,而且数据基本不变化

1. 安装

pip install drf-extensions

2. 使用方法

1. 直接添加装饰器
from rest_framework_extensions.cache.decorators import cache_response

class CityView(views.APIView):
    @cache_response()
    def get(self, request, *args, **kwargs):
        ...
# cache_response装饰器可以接收两个参数
@cache_response(timeout=60*60, cache='default')
  • timeout 缓存时间
  • cache 缓存使用的Django缓存后端(即CACHES配置中的键名称)

默认配置设置:

# settings.py

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

注意,cache_response装饰器既可以装饰在类视图中的get方法上,也可以装饰在REST framework扩展类提供的list或retrieve方法上。使用cache_response装饰器无需使用method_decorator进行转换。

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

用于缓存返回列表数据的视图,与ListModelMixin扩展类配合使用,实际是为list方法添加了cache_response装饰器

  • RetrieveCacheResponseMixin

用于缓存返回单一数据的视图,与RetrieveModelMixin扩展类配合使用,实际是为retrieve方法添加了cache_response装饰器

  • CacheResponseMixin

为视图集同时补充List和Retrieve两种缓存,与ListModelMixin和RetrieveModelMixin一起配合使用。

三个扩展类都是在rest_framework_extensions.cache.mixins中。

你可能感兴趣的:(十、DRF缓存使用)