Backend Engineer: Weird Behavior of Django Site Wide Caching

2019-03-13 00:51:28.338847+00:00

I need my site wide cache to never timeout.

I plan to give timeout later when I see a Django that view needs it, and the timeout will be added to that Django view only.

To achieve that I tried to set this setting value:

CACHE_MIDDLEWARE_SECONDS = None

However, doing that will give me this error:

Internal Server Error: /en-us/blog/
Traceback (most recent call last):
  File "/home/aldian/.virtualenv/afcom/lib/python3.7/site-packages/Django-2.2b1-py3.7.egg/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/aldian/.virtualenv/afcom/lib/python3.7/site-packages/Django-2.2b1-py3.7.egg/django/utils/deprecation.py", line 96, in __call__
    response = self.process_response(request, response)
  File "/home/aldian/.virtualenv/afcom/lib/python3.7/site-packages/Django-2.2b1-py3.7.egg/django/middleware/cache.py", line 108, in process_response
    patch_response_headers(response, timeout)
  File "/home/aldian/.virtualenv/afcom/lib/python3.7/site-packages/Django-2.2b1-py3.7.egg/django/utils/cache.py", line 241, in patch_response_headers
    if cache_timeout < 0:
TypeError: '<' not supported between instances of 'NoneType' and 'int'

Removing CACHE_MIDDLEWARE_SECONDS from my settings is not an option. Doing that will use the value from django.conf.global_settings.CACHE_MIDDLEWARE_SECONDS, which is 600 seconds.

So I think the workaround is to set CACHE_MIDDLEWARE_SECONDS to a very large integer value.

I would like to know from the Django team, was it an intentional design decision to disallow None value from CACHE_MIDDLEWARE_SECONDS?

If it was by design, it looks contradictory to the fact that we are allowed to put None to cache storage settings timeout:

It would be great if I can see the link to the page explaining the decision.

Granular Vary-Header & Per-View Redis Caching in Django

Replace global UpdateCacheMiddleware site-wide caching with explicit per-route cache keys scoped by locale, authentication state, and tenant ID. See Freelance Python & Django Programmer Guide.


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs