Django KEY_PREFIX vs CACHE_MIDDLEWARE_KEY_PREFIX

2.7k Views Asked by At

Until now I have been I have been using a single memcached instance for my 4 sites. On three of them I use a KEY_PREFIX because the documentation implied that I need to do that. Everything has been fine but now I need to periodically purge the list view (like when I add an entry). I found an way to purge the the page and was reviewing how it works when I ran into CACHE_MIDDLEWARE_KEY_PREFIX and now I'm confused.

  1. It appears that KEY_PREFIX is never used except when you define manually a key then it's actually used. Is this a true statement? Specifically the documentation about using KEY_PREFIX appears to be inaccurate?

  2. It appears that I should do this in my settings file to make sure they are aligned but I don't want to duplicate the key (demo:demo:). Will this infact duplicate it?

    KEY_PREFIX = CACHE_MIDDLEWARE_KEY_PREFIX = 'demo:'

I would really like to understand how these two mechanisms work. I'm starting to suspect that they really are different

1

There are 1 best solutions below

0
On

I don't think you don't quite have it right at the moment.

For your point 1, KEY_PREFIX is the most important of the settings when sharing the same cache using different django installs, but it's used like this:

CACHES = {
    'default': {
        "BACKEND": "redis_cache.cache.RedisCache",
        "LOCATION": "127.0.0.1:6379:1",
        "KEY_PREFIX": 'site-cache-prefix',
        "OPTIONS": {
            "CLIENT_CLASS": "redis_cache.client.DefaultClient",
        }
    }
}

That means each django instance is going to be using a different prefix when accessing the cache. This is probably what you want. If you did want to specifically share cache between your sites then adding another cache alias named 'shared' would probably be the way to go.

CACHE_MIDDLEWARE_KEY_PREFIX is used specifically for django's cache middleware and it will be used as well as the KEY_PREFIX I believe.