Search code examples
djangocachingdjango-rest-framework

Django cache doesn't invalidate on change


A cached page should be invalidated when something changes at the underlying resource. Django implements "site-wide" caching and I used this guide to setup my caching infrastructure (locally to test for now).

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    }
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
CACHE_TTL = 60 * 60 * 1
CACHE_MIDDLEWARE_SECONDS = CACHE_TTL

When I run my tests now, it works too well, as all tests fail, which change information in the database. Do I have to manually add a flag for cache invalidation? Should this even work (or are my settings wrong)? I saw this question, but in my case I don't use any decorators, but the side wide caching. Nevertheless I tested using the vary_on_headers('Authorisation',) which didn't change the test results.


Solution

  • As per this discussion in the Django forums, it seems like the automatic site caching isn't actually designed for this. It is more or less designed for caching a page until it expires, not until it is invalidated, because there is no way to invalidate a page manually.

    There is always the way of using the caching backend manually though.