pythondjangocachingmemcacheddjango-cache

Why is Django not using the specified cache backend?


As a simple test, I'm attempting to set the cache backend used by Django to something other than the default django.core.cache.backends.locmem.LocMemCache. I'm using a custom backend defined in the django-bmemcached package, which uses the python-binary-memcached module to access a Memcached instance with authentication. I've set the backend in the settings.py file, with the relevant snippet below:

CACHES = {
    'default': {
        'BACKEND': 'django_bmemcached.memcached.BMemcached',
        'LOCATION': <ip>:<port>,
        'OPTIONS': {
            'username': <username>,
            'password': <password>,
        }
    },
}

The settings.py file is being used by the application, but the default cache being used is not the specified cache backend:

>>> from django.conf import settings
>>> print(settings.CACHES)
{'default': {'BACKEND': 'django_bmemcached.memcached.BMemcached', 'LOCATION': <ip>:<port>, 'OPTIONS': {'username': <username>, 'password': <password>}}}
>>> from django.core.cache import caches
>>> print(caches['default'])
<django.core.cache.backends.locmem.LocMemCache object at 0x73bf66531720>

This isn't caused by a third party package overriding the cache backend, and the Memcached instance can be accessed and operations performed successfully if a client for the backend is instantiated: bmemcached.Client(<ip>:<port>, <username>, <password>).

Using a different binding, such as pymemcache, and setting the backend to a Django supported django.core.cache.backends.memcached.PyMemcacheCache still results in the above issues described where the default cache being used is not the specified cache backend.

If at all possible, I'd like to be able to simply use the Django cache API, from django.core.cache import cache, to be able to access the Memcached instance based on the backend set in settings.py.

Am I possibly missing some sort of setup? Is Django reverting back to the default in memory cache due to a silent exception? Any insight would be appreciated!


Solution

  • Within the settings.py file, before the cache settings were encountered, I instantiated a local client which made use of the Django cache API and thus set the cache backend to the default django.core.cache.backends.locmem.LocMemCache.

    Moving the cache settings up in the file before the instantiation of the local client allowed the correct django_bmemcached.memcached.BMemcached backend to be set as specified.