10

I'm trying to cache some of my DRF api calls in a CDN. I need the following headers Cache-Control:public, max-age=XXXX

This is pretty easy when you're using traditional django templating, you just add the @cache_page() @cache_control(public=True) decorators, but for DRF, I can't find anything similar. There's quite a bit about in mem caches, which I already have up, but I'd really like to get the CDN to take that load off my server all together, I'd like to cache the resulting queryset.

I'm also using modelViewSets if that matters for anything:

class EventViewSet(viewsets.ModelViewSet):

    serializer_class = EventViewSet
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    pagination_class = pagination.LimitOffsetPagination
    filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter,)
    filter_class = EventFilter
    search_fields = ('name','city','state')

    def get_queryset(self):
mcgruff14
  • 189
  • 12

3 Answers3

2

@method_decorator can be applied to the view class. When provided with a name argument, it will wrap that named method in instances of that class. What you want is something along the lines of:

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control

@method_decorator(cache_control(public=True, max_age=xxxx), name='dispatch')
class EventViewSet(viewsets.ModelViewSet):
    ...
tomchuk
  • 121
  • 1
  • 3
1

Did you try:

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control

class EventViewSet(viewsets.ModelViewSet):

    @method_decorator(cache_control(private=False, max_age=xxxx)
    def dispatch(self, request, *args, **kwargs):
        return super(EventViewSet, self).dispatch(request, *args, **kwargs)
leech
  • 7,950
  • 6
  • 60
  • 72
0

Update: I never solved the problem within Django or Django Rest Framework. I ended up setting the headers in our nginx conf file.

mcgruff14
  • 189
  • 12