缓存 (Caching)
某个女人很敏锐,但几乎没有记忆……她记得足够多的工作,她努力工作。——丽迪雅-戴维斯
REST Framework 中的缓存与 Django 中提供的缓存实用程序配合良好。
使用具有 apiview 和 viewsets 的缓存
Django 提供了一个 method_decorator
来使用具有基于类的视图的装饰器。这可以与其他缓存装饰器一起使用,例如 cache_page
和 vary_on_cookie
。
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets
class UserViewSet(viewsets.Viewset):
# 为每个用户缓存请求的 url 2小时
@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):
# 请求 url 的缓存页面
@method_decorator(cache_page(60*60*2))
def get(self, request, format=None):
content = {
'title': 'Post title',
'body': 'Post content'
}
return Response(content)
注意:cache_page
装饰器仅缓存状态为 200 的 GET
和 HEAD
响应。