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
.
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets
class UserViewSet(viewsets.ViewSet):
# Cache requested url for each user for 2 hours
@method_decorator(cache_page(60*60*2))
@method_decorator(vary_on_cookie)
def list(self, request, format=None):
content = {
'user_feed': request.user.get_user_feed()
}
return Response(content)
class PostView(APIView):
# Cache page for the requested url
@method_decorator(cache_page(60*60*2))
def get(self, request, format=None):
content = {
'title': 'Post title',
'body': 'Post content'
}
return Response(content)
NOTE: The cache_page
decorator only caches theGET
and HEAD
responses with status 200.
当前内容版权归 Django REST 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Django REST .