Rest-framework专栏讲解(十七):Caching

·  阅读 1274

MedusaSorcerer的博客


点击跳转到 Rest-Framework 专栏目录

将 cache 与 APIview 和 viewset 一起使用

Django提供了一个 method_decorator 来使用基于类的视图的装饰器, 这可以与其他缓存装饰器一起使用,例如 cache_pagevary_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)
复制代码

注意:cache_page decorator 只缓存状态为 200GETHEAD 响应。

分类:
代码人生
标签:
分类:
代码人生
标签:
收藏成功!
已添加到「」, 点击更改