1.安装包
pip install drf-extensions pip install django-redis pip install django-redis-cache
2.配置redis
# 配置缓存为redis CACHES = { 'default': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', "OPTIONS": { "CLIENT_CLASS": "redis_cache.client.DefaultClient", }, }, }
3.配置drf-extensions
# DRF扩展 REST_FRAMEWORK_EXTENSIONS = { # 缓存时间 'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 60, # 缓存存储 'DEFAULT_USE_CACHE': 'default', }
4.简单使用
from rest_framework_extensions.cache.mixins import CacheResponseMixin class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): pass