Details
Django has a decorator for a view function, called never_cache(), which manipulates the HTTP response headers to ensure that the browser will not cache the returned contents.
Sometimes it would be nice to control the actions of never_cache(). For example, while a system is under development, with constantly changing content, it is helpful to disable caching, and then turn it back on without having to make code changes. It is straightforward to do this, by wrapping never_cache() in another decorator, whose operation is controlled externally.
Python decorators are explained at https://pythonbasics.org/decorators/, to pick one of many tutorials. For exhaustive detail, the PEP https://peps.python.org/pep-0318/ goes into all the details.
The decorator wraps the function it is decorating, and creates another function which takes the original function’s place. Then the decorator can act on the original’s inputs or outputs.
In this GitHub gist, https://gist.github.com/robert-field/fddea81cbccc1df6254dab4d53f22c48, a Django settings entry called NO_CACHING is used, with a default value of False.
In @control_caching, the Boolean value means either the view function is passed throw, or is wrapped by Django’s @never_cache decorator.
The Code
def control_caching(func):
"""This can control whether Django's never_cache is active.
It can be used as a decorator. For example
@control_never_cache
def some_view(request):
# The code for some_view here
"""
def runner(*args, **kwargs):
# Can replace the getattr() call with any other true/false value
if getattr(settings, "NO_CACHING", False):
return (func)(*args, **kwargs)
else:
# Django decorator @never_cache
return never_cache(func)(*args, **kwargs)
return runner
Also: A Different Kind of Caching
It’s worth mentioning that Python has a built in decorator @cache, part of functools. This has nothing to do with Django or HTTP, but caches function values, which can yield significant speedups in many cases. Fibonacci, are you listening?