1
0
mirror of https://github.com/django/django.git synced 2025-10-24 06:06:09 +00:00

Fixed #6464 -- Added incr() and decr() operations on cache backends. Atomic on Memcache; implemented as a 2 stage retrieve/update on other backends. Includes refactor of the cache tests to ensure all the backends are actually tested, and a fix to the DB cache backend that was discovered as a result. Thanks to Michael Malone for the original patch.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@10031 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Russell Keith-Magee
2009-03-11 13:27:03 +00:00
parent 1d8e6eae34
commit 638dbc3e83
6 changed files with 239 additions and 41 deletions

View File

@@ -65,6 +65,24 @@ class BaseCache(object):
"""
return self.get(key) is not None
def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
if key not in self:
raise ValueError, "Key '%s' not found" % key
new_value = self.get(key) + delta
self.set(key, new_value)
return new_value
def decr(self, key, delta=1):
"""
Subtract delta from value in the cache. If the key does not exist, raise
a ValueError exception.
"""
return self.incr(key, -delta)
def __contains__(self, key):
"""
Returns True if the key is in the cache and has not expired.

View File

@@ -64,6 +64,7 @@ class CacheClass(BaseCache):
cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table, [key, encoded, str(exp)])
except DatabaseError:
# To be threadsafe, updates/inserts are allowed to fail silently
transaction.rollback()
return False
else:
transaction.commit_unless_managed()

View File

@@ -45,3 +45,8 @@ class CacheClass(BaseCache):
def close(self, **kwargs):
self._cache.disconnect_all()
def incr(self, key, delta=1):
return self._cache.incr(key, delta)
def decr(self, key, delta=1):
return self._cache.decr(key, delta)