|
| 1 | +# Caching |
| 2 | + |
| 3 | +> A certain woman had a very sharp conciousness but almost no |
| 4 | +> memory ... She remembered enough to work, and she worked hard. |
| 5 | +> - Lydia Davis |
| 6 | +
|
| 7 | +Caching in REST Framework works well with the cache utilities |
| 8 | +provided in Django. |
| 9 | + |
| 10 | +--- |
| 11 | + |
| 12 | +## Using cache with apiview and viewsets |
| 13 | + |
| 14 | +Django provides a [`method_decorator`][decorator] to use |
| 15 | +decorators with class based views. This can be used with |
| 16 | +with other cache decorators such as [`cache_page`][page] and |
| 17 | +[`vary_on_cookie`][cookie]. |
| 18 | + |
| 19 | +```python |
| 20 | +from rest_framework.response import Response |
| 21 | +from rest_framework.views import APIView |
| 22 | +from rest_framework import viewsets |
| 23 | + |
| 24 | +class UserViewSet(viewsets.Viewset): |
| 25 | + |
| 26 | + # Cache requested url for each user for 2 hours |
| 27 | + @method_decorator(cache_page(60*60*2)) |
| 28 | + @method_decorator(vary_on_cookie) |
| 29 | + def list(self, request, format=None): |
| 30 | + content = { |
| 31 | + 'user_feed': request.user.get_user_feed() |
| 32 | + } |
| 33 | + return Response(content) |
| 34 | + |
| 35 | +class PostView(APIView): |
| 36 | + |
| 37 | + # Cache page for the requested url |
| 38 | + @method_decorator(cache_page(60*60*2)) |
| 39 | + def get(self, request, format=None): |
| 40 | + content = { |
| 41 | + 'title': 'Post title', |
| 42 | + 'body': 'Post content' |
| 43 | + } |
| 44 | + return Response(content) |
| 45 | +``` |
| 46 | + |
| 47 | +**NOTE:** The [`cache_page`][page] decorator only caches the |
| 48 | +`GET` and `HEAD` responses with status 200. |
| 49 | + |
| 50 | + |
| 51 | +[django]: https://docs.djangoproject.com/en/dev/topics/cache/ |
| 52 | +[page]: https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache |
| 53 | +[cookie]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie |
| 54 | +[decorator]: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class |
0 commit comments