Django-redis缓存初步使用

https://django-redis-chs.readthedocs.io/zh_CN/latest/# redis中文文档

 

Django 版本支持

  • django-redis 3.8.x 支持 django 1.4, 1.5, 1.6, 1.7 (或许会有 1.8)
  • django-redis 4.4.x 支持 django 1.6, 1.7, 1.8, 1.9 和 1.10

 Redis Server 支持

  • django-redis 3.x.y 支持 redis-server 2.6.x 或更高
  • django-redis 4.x.y 支持 redis-server 2.8.x 或更高

 其他依赖

所有版本的 django-redis 基于 redis-py >= 2.10.0.

2. 用户指南

2.1 安装

安装 django-redis 最简单的方法就是用 pip :

pip install django-redis

2.2 作为 cache backend 使用配置

为了使用 django-redis , 你应该将你的 django cache setting 改成这样:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

 

为了更好的互操作性并使连接字符串更加 “标准”, 从 3.8.0 开始 django-redis 使用 redis-py native url notation 作为连接字符串.

2.3 作为 session backend 使用配置

Django 默认可以使用任何 cache backend 作为 session backend, 将 django-redis 作为 session 储存后端不用安装任何额外的 backend

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

 

 

 

在DRF中使用缓存

http://chibisov.github.io/drf-extensions/docs/

pip3 install drf-extensions

 

CacheResponseMixin

It is common to cache standard viewset retrieve and list methods. That is why CacheResponseMixin exists. Just mix it into viewset implementation and those methods will use functions, defined in REST_FRAMEWORK_EXTENSIONS settings:

  • "DEFAULT_OBJECT_CACHE_KEY_FUNC" for retrieve method
  • "DEFAULT_LIST_CACHE_KEY_FUNC" for list method

By default those functions are using DefaultKeyConstructor and extends it:

  • With RetrieveSqlQueryKeyBit for "DEFAULT_OBJECT_CACHE_KEY_FUNC"
  • With ListSqlQueryKeyBit and PaginationKeyBit for "DEFAULT_LIST_CACHE_KEY_FUNC"

Mixin example :

from myapps.serializers import UserSerializer
from rest_framework_extensions.cache.mixins import CacheResponseMixin

class UserViewSet(CacheResponseMixin, viewsets.ModelViewSet):
    serializer_class = UserSerializer

 

Settings配置过期时间

REST_FRAMEWORK_EXTENSIONS = {
    'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 15
}

 

 

 

 

posted on 2019-06-16 20:43  Orvis  阅读(178)  评论(0编辑  收藏  举报

导航