Thanks to @rdegges suggestions , I was able to find a great way to do this.
I follow this paradigm:
- Cached template fragments and API calls for five minutes (or longer)
- Invalid cache every time new data is added.
- Simple cache invalidation is better than deletion when saving, because new cached data is generated automatically and organically when no cached data is found.
- Manually cancel the cache after I have done a full update (say, from a tweet search), and not for every save of the object.
- This can lead to invalidation of caching several times, but on the other hand it is not so automatic.
Here is all the code you need to do as follows:
from django.conf import settings from django.core.cache import get_cache from django.core.cache.backends.memcached import MemcachedCache from django.utils.encoding import smart_str from time import time class NamespacedMemcachedCache(MemcachedCache): def __init__(self, *args, **kwargs): super(NamespacedMemcachedCache, self).__init__(*args, **kwargs) self.cache = get_cache(getattr(settings, 'REGULAR_CACHE', 'regular')) self.reset() def reset(self): namespace = str(time()).replace('.', '') self.cache.set('namespaced_cache_namespace', namespace, 0)
This works by installing a version or namespace on each entry in the cache and storing that version in the cache . Version is only the current era when reset() called.
You must specify your alternative cache without labels using settings.REGULAR_CACHE , so the version number can be stored in the cache without names (so that it will not be recursive!).
Whenever you add a bunch of data and want to clear the cache (if you set this as the default cache), just do:
from django.core.cache import cache cache.clear()
You can access any cache with:
from django.core.cache import get_cache some_cache = get_cache('some_cache_key')
Finally, I recommend that you do not put the session in this cache. You can use this method to change the cache key for your session. (As settings.SESSION_CACHE_ALIAS ).
Dave
source share