The Vary header defines which request header the cache mechanism should take into account when building its cache key value. For example, if the content of a Web page depends on the user's language preference, the page is called different depending on the language.
By default, the Django cache system uses the requested path (for example, "/stories/2005/jun/23/bank_robbed/") to create its cache key. This means that each request will use the same cached version, regardless of the client cookie and language configuration. Unless you use the Vary header notification caching mechanism, the page output differs depending on the settings of the cookie, language, and so on in the request.
To do this with Django, you can use the handy vary_on_headers view adorner, as shown below:
From django.views.decorators.vary import vary_on_headers# Python 2.3 syntax.def My_view (Request): # ... my_view = Vary_on_headers (My_view, ' user-agent ') # Python 2.4+ decorator syntax. @vary_on_headers (' user-agent ') def my_view ( Request): # ...
In this case, caching mechanisms, such as Django's own cache middleware, will cache a separate page version for each individual user's browser.
The benefit of using the vary_on_headers adorner instead of manually setting the vary header (using code like response[' vary ' = ' user-agent ') is that the decorator is added on top of (possibly already existing) vary, rather than starting from zero, And may overwrite settings that already exist at that point.
You can pass in multiple headers to vary_on_headers ():
@vary_on_headers (' user-agent ', ' Cookie ') def my_view (Request): # ...
This code tells the upstream cache to do something different, meaning that each combination of user-agent and cookies should get its own cache value. For example, a request to use Mozilla as a user-agent and Foo=bar as a cookie value should be treated as a different request than using Mozilla as a user-agent and Foo=ham request.
Because it is very common to differentiate between treats based on cookies, there are Vary_on_cookie adorners. The following two views are equivalent:
@vary_on_cookiedef My_view (Request): # @vary_on_headers (' Cookie ') def my_view (Request): # ...
Incoming vary_on_headers headers are case insensitive; "user-agent" is identical to "user-agent".
You can also use the Help function directly: Django.utils.cache.patch_vary_headers. This function sets or increments the Vary header, for example:
From Django.utils.cache import patch_vary_headersdef my_view (Request): # ... Response = Render_to_response (' template_name ', context) patch_vary_headers (response, [' Cookie ']) return Response
Patch_vary_headers takes a HttpResponse instance as the first argument, a case insensitive header name list or a tuple as the second parameter.