Caching

A certain woman had a very sharp consciousness but almost nomemory … She remembered enough to work, and she worked hard.- Lydia Davis

Caching in REST Framework works well with the cache utilitiesprovided in Django.


Using cache with apiview and viewsets

Django provides a method_decorator to usedecorators with class based views. This can be used withother cache decorators such as cache_page andvary_on_cookie.

  1. from django.utils.decorators import method_decorator
  2. from django.views.decorators.cache import cache_page
  3. from django.views.decorators.vary import vary_on_cookie
  4. from rest_framework.response import Response
  5. from rest_framework.views import APIView
  6. from rest_framework import viewsets
  7. class UserViewSet(viewsets.ViewSet):
  8. # Cache requested url for each user for 2 hours
  9. @method_decorator(cache_page(60*60*2))
  10. @method_decorator(vary_on_cookie)
  11. def list(self, request, format=None):
  12. content = {
  13. 'user_feed': request.user.get_user_feed()
  14. }
  15. return Response(content)
  16. class PostView(APIView):
  17. # Cache page for the requested url
  18. @method_decorator(cache_page(60*60*2))
  19. def get(self, request, format=None):
  20. content = {
  21. 'title': 'Post title',
  22. 'body': 'Post content'
  23. }
  24. return Response(content)

NOTE: The cache_page decorator only caches theGET and HEAD responses with status 200.