Fighting client-side caching in Django

前端 未结 7 885
傲寒
傲寒 2020-11-27 13:18

I\'m using the render_to_response shortcut and don\'t want to craft a specific Response object to add additional headers to prevent client-side caching.

I\'d like to

相关标签:
7条回答
  • 2020-11-27 14:20

    To supplement existing answers. Here is a decorator that adds additional headers to disable caching:

    from django.views.decorators.cache import patch_cache_control
    from functools import wraps
    
    def never_ever_cache(decorated_function):
        """Like Django @never_cache but sets more valid cache disabling headers.
    
        @never_cache only sets Cache-Control:max-age=0 which is not
        enough. For example, with max-axe=0 Firefox returns cached results
        of GET calls when it is restarted.
        """
        @wraps(decorated_function)
        def wrapper(*args, **kwargs):
            response = decorated_function(*args, **kwargs)
            patch_cache_control(
                response, no_cache=True, no_store=True, must_revalidate=True,
                max_age=0)
            return response
        return wrapper
    

    And you can use it like:

    class SomeView(View):
        @method_decorator(never_ever_cache)
        def get(self, request):
            return HttpResponse('Hello')
    
    0 讨论(0)
提交回复
热议问题