Skip to content

Instantly share code, notes, and snippets.

@ashchristopher
Created December 16, 2009 22:50
Show Gist options
  • Save ashchristopher/258284 to your computer and use it in GitHub Desktop.
Save ashchristopher/258284 to your computer and use it in GitHub Desktop.
Overloading the python-memcahce delete() function in a django project since it isn't supported.
Initially wanted to do this:
from django.core.cache.backends.memcached import CacheClass
class DeletableCache(object):
"""
The memcache library doesnt seem to support delete. This is a mixin to fake it.
In [3]: cache.set('oo', 123, 1000)
In [4]: cache.get('oo')
Out[4]: 123
In [5]: cache.delete('oo')
In [6]: cache.get('oo')
Out[6]: 123
"""
def delete(self, key):
"""
We will invalidate by setting the time-to-live to -1 second, effectivly deleting it.
"""
print 'deleting %s' %key
self.set(key, None, -1)
CacheClass.__bases__ += (DeletableCache,)
But you can't overload existing methods using mixins, so I did the following which works:
from django.core.cache.backends.memcached import CacheClass
def delete(self, key):
"""
The memcache library doesnt seem to support delete. This is a mixin to fake it.
In [3]: cache.set('oo', 123, 1000)
In [4]: cache.get('oo')
Out[4]: 123
In [5]: cache.delete('oo')
In [6]: cache.get('oo')
Out[6]: 123
We will invalidate by setting the time-to-live to -1 second, effectivly deleting it.
"""
self.set(key, None, -1)
setattr(CacheClass, 'delete', delete)
Output:
In [1]: from django.core.cache import cache
In [2]: cache.set('oo', 123, 10000)
In [3]: cache.get('oo')
Out[3]: 123
In [4]: cache.delete('oo')
deleting oo
In [5]: cache.get('oo')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment