| 1 |
from functools import wraps |
| 2 |
|
| 3 |
from asgiref.sync import iscoroutinefunction |
| 4 |
|
| 5 |
from django.utils.cache import patch_vary_headers |
| 6 |
|
| 7 |
|
| 8 |
def vary_on_headers(*headers): |
| 9 |
""" |
| 10 |
A view decorator that adds the specified headers to the Vary header of the |
| 11 |
response. Usage: |
| 12 |
|
| 13 |
@vary_on_headers('Cookie', 'Accept-language') |
| 14 |
def index(request): |
| 15 |
... |
| 16 |
|
| 17 |
Note that the header names are not case-sensitive. |
| 18 |
""" |
| 19 |
|
| 20 |
def decorator(func): |
| 21 |
if iscoroutinefunction(func): |
| 22 |
|
| 23 |
async def _view_wrapper(request, *args, **kwargs): |
| 24 |
response = await func(request, *args, **kwargs) |
| 25 |
patch_vary_headers(response, headers) |
| 26 |
return response |
| 27 |
|
| 28 |
else: |
| 29 |
|
| 30 |
def _view_wrapper(request, *args, **kwargs): |
| 31 |
response = func(request, *args, **kwargs) |
| 32 |
patch_vary_headers(response, headers) |
| 33 |
return response |
| 34 |
|
| 35 |
return wraps(func)(_view_wrapper) |
| 36 |
|
| 37 |
return decorator |
| 38 |
|
| 39 |
|
| 40 |
vary_on_cookie = vary_on_headers("Cookie") |
| 41 |
vary_on_cookie.__doc__ = ( |
| 42 |
'A view decorator that adds "Cookie" to the Vary header of a response. This ' |
| 43 |
"indicates that a page's contents depends on cookies." |
| 44 |
) |