I’m using django’s cache to cache views in a GIS application, specifically to cache map tile views. The cache is a quick and easy way to avoid hitting the DB to calculate map tiles on each request.
One small issue is that django’s cache won’t cache http 204 (no data) responses. That’s suboptimal though, because when calculating tiles, even a response with no data can be expensive for the DB to calculate, and would benefit from caching.
I worked around it for myself by subclassing the CacheMiddleware with this object of beauty, which works and caches these responses properly:
## Create our own thin layer around Django caching middleware so we can cache empty responses. class MyCacheMiddleware(CacheMiddleware): def process_response(self, request, response): if response.status_code == 204: # Fudge the response so that it's cacheable. response.status_code = 200 resp = super().process_response(request, response) resp.status_code = 204 return resp else: return super().process_response(request, response)
One problem with this is I end up returning a status code of 200 on a cache hit, when I should be returning a 204…
But I wanted to ask – is there a principled reason why we don’t cache 204 responses?