11.7.drf的缓存

drf-extensions

Installation:

pip3 install drf-extensions

CacheResponseMixin

It is common to cache standard viewsetarrow-up-right 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 settingsarrow-up-right:

  • "DEFAULT_OBJECT_CACHE_KEY_FUNC" for retrieve method

  • "DEFAULT_LIST_CACHE_KEY_FUNC" for list method

By default those functions are using DefaultKeyConstructorarrow-up-right 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:

设置cache过期时间

Last updated