[Solved]-Django Rest Framework Cache Headers

5👍

@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):
    ...

3👍

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

1👍

It seems that django.views.decorators.cache was deprecated after Django 3.2 (although I wasn’t able to confirm the exact version of deprecation, not even in Django’s deprecation timeline). This makes @tomchuk’s answer obsolete as of november 2023.

A possible alternative, with similar usage, is to implement a middleware that leverages the django.utils.cache.patch_cache_control, and attach it to the view using one of django.utils.decorators.decorator_from_middleware{,_with_args}:

from django.utils.cache import patch_cache_control
from django.utils.decorators import (
    decorator_from_middleware_with_args,
    method_decorator,
)

class CacheHeaderMiddleware:
    def __init__(self, func, **kwargs):
        self.options = kwarg

    def process_response(self, request, response):
        patch_cache_control(response, **self.options)
        return response

control_cache = decorator_from_middleware_with_args(CacheHeaderMiddleware)

@method_decorator(control_cache(max_age=3600), name='dispatch')
class TheViewClass:
    ...

Note that, as in @tomchuk answer, we still need to use method_decorator to turn a function decorator into a class decorator. Note also that the decorators decorator_from_middleware{,_with_args} expect a

middleware that’s compatible with the old style of Django 1.9 and
earlier (having methods like process_request(), process_exception(),
and process_response()).

More information about different styles of middleware can be found here.

-1👍

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

Leave a comment