【djangorestframework】14、Caching(缓存)
缓存(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响应。
本文来自博客园,作者:郭祺迦,转载请注明原文链接:https://www.cnblogs.com/guojie-guojie/p/16190729.html

浙公网安备 33010602011771号