mirror of
https://github.com/django/django.git
synced 2025-10-24 14:16: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:
18
django/core/cache/backends/base.py
vendored
18
django/core/cache/backends/base.py
vendored
@@ -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.
|
||||
|
||||
1
django/core/cache/backends/db.py
vendored
1
django/core/cache/backends/db.py
vendored
@@ -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()
|
||||
|
||||
5
django/core/cache/backends/memcached.py
vendored
5
django/core/cache/backends/memcached.py
vendored
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user