> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/python/django-rest-framework/11.7.drf-de-huan-cun.md).

# 11.7.drf的缓存

drf-extensions

## Installation:

```bash
pip3 install drf-extensions
```

CacheResponseMixin

It is common to cache standard [viewset](http://www.django-rest-framework.org/api-guide/viewsets) `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](http://chibisov.github.io/drf-extensions/docs/#settings):

* *"DEFAULT\_OBJECT\_CACHE\_KEY\_FUNC"* for `retrieve` method
* *"DEFAULT\_LIST\_CACHE\_KEY\_FUNC"* for `list` method

By default those functions are using [DefaultKeyConstructor](http://chibisov.github.io/drf-extensions/docs/#default-key-constructor) 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:

```python
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:

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

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

设置cache过期时间

```python
REST_FRAMEWORK_EXTENSIONS = {
    'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 15
}
```
