在Django REST framework中使用缓存,可以通过drf-extensions扩展来实现。
关于扩展使用缓存的文档,可参考链接 http://chibisov.github.io/drf-extensions/docs/#caching
安装
pip3 install drf-extensions
使用
- Setting.py配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
# 定义django中redis的位置,指定用redis的db1
"LOCATION": "redis://0.0.0.0:6379/1",
"OPTIONS": {
# django使用redis的默认客户端来进行操作.
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
REST_FRAMEWORK_EXTENSIONS = {
# 缓存时间
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 10,
# 缓存存储
'DEFAULT_USE_CACHE': 'default',
}
# ①我们定义一个cache(本地缓存来存储信息,cahe指定的是redis
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# ②指定本地的session使用的本地缓存名称是'default'
SESSION_CACHE_ALIAS = "default"
drf-extensions扩展对于缓存提供了三个扩展类:
- ListCacheResponseMixin ,用于缓存返回列表数据的视图,与ListModelMixin扩展类配合使用,实际是为list方法添加了cache_response装饰器;
- RetrieveCacheResponseMixin ,用于缓存返回单一数据的视图,与RetrieveModelMixin扩展类配合使用,实际是为retrieve方法添加了cache_response装饰器;
- CacheResponseMixin ,为视图集同时补充List和Retrieve两种缓存,与ListModelMixin和RetrieveModelMixin一起配合使用(我选择使用这种)。
三个扩展类都是在rest_framework_extensions.cache.mixins中。
from rest_framework_extensions.cache.mixins import CacheResponseMixin
class CustomerViewSet(CacheResponseMixin,MyModelViewSet):
# class CustomerViewSet(MyModelViewSet):
queryset =Customer.objects.all()
serializer_class = CustomerSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('Name', 'Phone','DialStatu')
重启服务,访问customer或者对customer数据进行增删改查(但是一般将缓存设置在经常用到但不容易被更改的数据上-只读数据),数据就会写入redis。