6

I just want to use caching to a ViewSet too slow :(, with Django REST Framework.

I've do this :

...
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
...
class PRPKViewSet(viewsets.ModelViewSet):
    serializer_class = PrpkSerializer
    queryset = Prpk.objects.all().order_by('begin')
    # Authentification !
    permission_classes = (IsAuthenticated,)
    # Only 'get' method
    http_method_names = ['get']

    # Cache requested url for each user for 2 hours
    # @method_decorator(vary_on_cookie)
    @method_decorator(cache_page(60*2))
    def get_queryset(self):
        """ allow rest api to filter by submissions """
        queryset = Prpk.objects.all().order_by('begin')
        highway = self.request.query_params.get('highway', None)
        if highway is not None:
            queryset = queryset.filter(highway=highway)

        return queryset

But when querying, I've this error :

TypeError: _wrapped_view() missing 1 required positional argument: 'request'

Memcached is installed.

So, can I caching just one ViewSet (not using an extension ?) ?

Thanks a lot.

F.

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
fabrice
  • 1,399
  • 1
  • 15
  • 27

1 Answers1

17

Decorate dispatch instead of get_queryset.

@method_decorator(cache_page(60*2))
def dispatch(self, request, *args, **kwargs):
    return super().dispatch(request, *args, **kwargs)
Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
  • Hi, Thanks. I've just add the "dispatch" function above "get_queryset" but I've this error : "if response.streaming or response.status_code not in (200, 304):AttributeError: 'NoneType' object has no attribute 'streaming'" – fabrice Jul 24 '18 at 13:34
  • 1
    my bad : missing "return" :). First query : 11 s, second call : 431 ms :). It's working. For now, how can I see the pages currently cached, please ? – fabrice Jul 24 '18 at 14:08
  • @fabrice true, I missed `return`, fixed. Look into https://stackoverflow.com/questions/9048257/get-list-of-cache-keys-in-django to see how to get chached pages, as that's a different question. – Dušan Maďar Jul 24 '18 at 14:41
  • How do you invalidate `cache_page` ? and test if its really working – Ryan Aquino Sep 20 '21 at 03:24
  • IMPORTANT NOTE: If you have authentication on your viewset then the cache check will be done before auth check which is really dangerous. – Saleh Oct 19 '21 at 20:36