Search code examples
djangocache-control

Dynamic control over cache max age at request time in Django


In Django I can use something like this to manage cache's max-age for a request:

from django.views.decorators.cache import cache_control

@cache_control(max_age=3600)
def my_view(request):
    # ...

How can I set a different max_age value inside the view function so that it can depend on what the request content is?

Example:

def my_view(request):
    if is_good_to_cache(request):
        # set max_age to 36000
    else:
        # set max_age to 42 
    # ... 

Solution

  • As cache_control is taking advantage of patch_cache_control internally, it's OK to directly put:

    from django.utils.cache import patch_cache_control
    
    def my_view(request):
        if is_good_to_cache(request):
            max_age = 36000
        else:
            max_age = 42 
        resp = render(...)
        patch_cache_control(resp, max_age=max_age)
        return resp