Cache framework support for 204 response?

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?

I feel like this is an oversight and we could easily extend the middleware to cache 204’s as well by default.

Yeah I think it might be an oversight.

if we fix this we should probably also cache the response code , so we return a 204 from the cache if the original response was a 204. does that sound right?

Yes, it wouldn’t be correct to change the status code.