• Home
  • Django
  • Cache View of personalized cache key

Cache View of personalized cache key

linkaiyi
Follow

Cache key can be modified with vary header

It seems that what you need is vary decorators. For example you can use this code:

from django.views.decorators.vary import vary_on_headers

@vary_on_headers('Cookie', 'User-Agent')
def my_view(request):
    # do some stuff

Or equivalently

from django.views.decorators.vary import vary_on_cookie

@vary_on_cookie
def my_view(request):
    # do some stuff

The response will be cached unless cookies change (this happens when for example a user logges in). There are other interesting things you can do with vary. See this article or the documentation for more details.

You can also try doing this in a custom middleware so you won’t have to add these decorators on every view. This can be done like this:

from django.utils.cache import add_never_cache_headers

class DisableClientSideCachingMiddleware(object):
    def process_response(self, request, response):
        if request.user.is_authenticated():
            add_never_cache_headers(response)
        return response

I’ve borrowed the code from here. Now you only add the middleware and you don’t have to worry about anything else.

do not cache for some view

You can achieve this using the cache_control decorator. Example from the documentation:

from django.views.decorators.cache import never_cache

@never_cache
def myview(request):
   # ...
Object has 0 attachments

Was this article helpful?

This article is viewed 8 times!

Recent Viewed Articles

Related Articles

0 Comments

Leave a Comment

Support