eugene
eugene

Reputation: 41665

DRF, caching for as_view()?

In my view, I often use APIView's as_view() to generate json.

I'd like to cache the response and tried the following but it won't work

def some_complex_view(self, request, *args, **kwargs):
    pass

@method_decorator(cache_page(60, key_prefix='drf'))
def dispatch(self, request, *args, **kwargs):
   return super().dispatch(request, *args, **kwargs)

Then, I call

def my_view(request, *args, **kwargs): 
    json_data = MyViewSet.as_view({'get': 'some_complex_view'})(request, format='json')

    data = {
       'my_data': json_data
    }
    return render(request, 'my_template.html', data)

It correctly caches when I request the view using browser, but it won't when using as_view()

Upvotes: 2

Views: 818

Answers (1)

Sathish Kumar VG
Sathish Kumar VG

Reputation: 2172

There are a few strategies listed in the CBV docs:

Add the decorator in your urls.py route, e.g., login_required(ViewSpaceIndex.as_view(..)) Decorate your CBV's dispatch method with a method_decorator e.g.,

from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class MyViewSet(TemplateView):
    template_name = 'secret.html'

Before Django 1.9 you can't use method_decorator on the class, so you have to override the dispatch method:

class MyViewSet(TemplateView):

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MyViewSet, self).dispatch(*args, **kwargs)

Upvotes: 3

Related Questions