# 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
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://moluo.gitbook.io/notes/bian-cheng-xue-xi/python/django-rest-framework/11.7.drf-de-huan-cun.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
