Skip to content

Commit 82b8a64

Browse files
authored
docs: add example for caching (encode#7118)
1 parent 95ae92e commit 82b8a64

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

docs/api-guide/caching.md

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,21 @@ provided in Django.
1313

1414
Django provides a [`method_decorator`][decorator] to use
1515
decorators with class based views. This can be used with
16-
other cache decorators such as [`cache_page`][page] and
17-
[`vary_on_cookie`][cookie].
16+
other cache decorators such as [`cache_page`][page],
17+
[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers].
1818

1919
```python
2020
from django.utils.decorators import method_decorator
2121
from django.views.decorators.cache import cache_page
22-
from django.views.decorators.vary import vary_on_cookie
22+
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
2323

2424
from rest_framework.response import Response
2525
from rest_framework.views import APIView
2626
from rest_framework import viewsets
2727

2828

2929
class UserViewSet(viewsets.ViewSet):
30-
31-
# Cache requested url for each user for 2 hours
30+
# With cookie: cache requested url for each user for 2 hours
3231
@method_decorator(cache_page(60*60*2))
3332
@method_decorator(vary_on_cookie)
3433
def list(self, request, format=None):
@@ -38,8 +37,18 @@ class UserViewSet(viewsets.ViewSet):
3837
return Response(content)
3938

4039

41-
class PostView(APIView):
40+
class ProfileView(APIView):
41+
# With auth: cache requested url for each user for 2 hours
42+
@method_decorator(cache_page(60*60*2))
43+
@method_decorator(vary_on_headers("Authorization",))
44+
def get(self, request, format=None):
45+
content = {
46+
'user_feed': request.user.get_user_feed()
47+
}
48+
return Response(content)
4249

50+
51+
class PostView(APIView):
4352
# Cache page for the requested url
4453
@method_decorator(cache_page(60*60*2))
4554
def get(self, request, format=None):
@@ -55,4 +64,5 @@ class PostView(APIView):
5564

5665
[page]: https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache
5766
[cookie]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie
67+
[headers]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_headers
5868
[decorator]: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class

0 commit comments

Comments
 (0)