11.7.drf的缓存

drf-extensions

Installation:

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"

You can change those settings for custom cache key generation:

REST_FRAMEWORK_EXTENSIONS = {
    'DEFAULT_OBJECT_CACHE_KEY_FUNC':
      'rest_framework_extensions.utils.default_object_cache_key_func',
    'DEFAULT_LIST_CACHE_KEY_FUNC':
      'rest_framework_extensions.utils.default_list_cache_key_func',
}

Mixin example usage:

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

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

设置cache过期时间

REST_FRAMEWORK_EXTENSIONS = {
    'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 15
}

Last updated

Was this helpful?