Search code examples
djangopinaxdjango-cache

How to apply Django cache control on included urls?


I have enabled site-wide Django caching, but the third-party apps I am using have not specified any cache-control expectations. So, I am guessing that their views will get cached.

The problem is that I do not want Django to cache the views of some apps. How do I apply url-level cache control on include()?

url(r"^account/", include("pinax.apps.account.urls")) #How to apply cache control here?

Solution

  • You can't. The per-site cache is achieved through middlewares which considers only request and response instead of specific view.

    However, you could achieve this by providing a patched django.middleware.cache.FetchFromCacheMiddleware.

    class ManagedFetchFromCacheMiddle(FetchFromCacheMiddleware):
        def process_request(self, request):
            if should_exempt(request):
                request._cache_update_cache = False
                return
            return super(ManagedFetchFromCacheMiddle, self).process_request(request)
    
    def should_exempt(request):
        """Any predicator to exempt cache on a request
        For your case, it looks like
    
        if request.path.startswith('/account/'):
            return True
        """
    

    Replace 'django.middleware.cache.FetchFromCacheMiddleware' with the path of the above in MIDDLEWARE_CLASSES.

    Maybe generic version of above is suitable for commiting patch to Django community =p