当前位置: 代码迷 >> 综合 >> Caching - Django REST framework
  详细解决方案

Caching - Django REST framework

热度:92   发布时间:2023-09-14 11:05:26.0

缓存-Django REST框架

缓存

一个女人有着敏锐的意识但几乎没有记忆..。她记得得够多了,工作也很努力。-莉迪亚·戴维斯

REST框架中的缓存与Django中提供的缓存实用程序工作得很好。


将缓存与像素视图和视图集一起使用

Django提供了一个method_decorator在基于类的视图中使用装饰器。这可以与其他缓存装饰器一起使用,例如cache_pagevary_on_cookie.

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsetsclass 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)

注:这个cache_page装饰者只缓存GETHEAD回复状态为200。

  相关解决方案