美文网首页
十、DRF缓存使用

十、DRF缓存使用

作者: battleMonkey | 来源:发表于2019-04-03 23:18 被阅读0次

使用时机:

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

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缓存使用

    使用时机: 1. 安装 2. 使用方法 1. 直接添加装饰器 timeout 缓存时间 cache 缓存使用的Dj...

  • 第十一天

    drf的缓存设置 django本身是支持缓存的,drf的缓存是在django缓存上的二次开发。安装drf exte...

  • Nginx-->性能优化-->使用DRF缓存+upstream

    Django后端调整 使用uri_hash配合Django中的drf-extensions扩展包增加缓存(当然原生...

  • Django + drf-extensions

    版本 注意 在使用drf-extensions中的缓存mixin时,首先需要继承rest_framework的mi...

  • DRF使用记录(一) 初体验

    drf使用记录(一) drf初体验 drf(Django REST framework) 下面简单体验一下drf ...

  • drf 一

    目录 1.drf简单使用 2.drf快速使用 2.1 views.py 2.2 serializer.py 2.3...

  • 查漏补缺

    Django drf listserializers的使用 source的使用

  • DRF 配置 Redis 缓存

    安装 Redis 在配置缓存前要先安装好 Redis ,Windows 版本下载地址: https://githu...

  • django-restful:缓存机制 drf-extensi

    配置第三方包 的缓存功能 github地址:https://github.com/chibisov/drf-e...

  • DRF十大组件

    DRF十大组认证实现 ##############################################...

网友评论

      本文标题:十、DRF缓存使用

      本文链接:https://www.haomeiwen.com/subject/mbxxiqtx.html