Code

Ticket #16858: locmem_incr_expiration_16858.diff

File locmem_incr_expiration_16858.diff, 2.2 KB (added by manfre, 2 years ago)

locmem cache's incr() will no longer change timeout to mimic memcached

Line 
1diff --git a/django/core/cache/backends/locmem.py b/django/core/cache/backends/locmem.py
2--- a/django/core/cache/backends/locmem.py
3+++ b/django/core/cache/backends/locmem.py
4@@ -15,6 +15,10 @@
5 _expire_info = {}
6 _locks = {}
7 
8+# Special timeout value used by incr and decr to instruct the cache to
9+# not change the existing timeout value
10+IGNORE_TIMEOUT = 'ignore'
11+
12 class LocMemCache(BaseCache):
13     def __init__(self, name, params):
14         BaseCache.__init__(self, params)
15@@ -71,7 +75,8 @@
16         if timeout is None:
17             timeout = self.default_timeout
18         self._cache[key] = value
19-        self._expire_info[key] = time.time() + timeout
20+        if timeout != IGNORE_TIMEOUT:
21+            self._expire_info[key] = time.time() + timeout
22 
23     def set(self, key, value, timeout=None, version=None):
24         key = self.make_key(key, version=version)
25@@ -84,6 +89,18 @@
26         finally:
27             self._lock.writer_leaves()
28 
29+    def incr(self, key, delta=1, version=None):
30+        """
31+        Add delta to value in the cache. If the key does not exist, raise a
32+        ValueError exception.
33+        """
34+        value = self.get(key, version=version)
35+        if value is None:
36+            raise ValueError("Key '%s' not found" % key)
37+        new_value = value + delta
38+        self.set(key, new_value, version=version, timeout=IGNORE_TIMEOUT)
39+        return new_value
40+
41     def has_key(self, key, version=None):
42         key = self.make_key(key, version=version)
43         self.validate_key(key)
44diff --git a/tests/regressiontests/cache/tests.py b/tests/regressiontests/cache/tests.py
45--- a/tests/regressiontests/cache/tests.py
46+++ b/tests/regressiontests/cache/tests.py
47@@ -822,6 +822,14 @@
48         self.assertEqual(mirror_cache.get('value1'), 42)
49         self.assertEqual(other_cache.get('value1'), None)
50 
51+    def test_incr_expiration(self):
52+        self.cache.set('val', 42, timeout=2)
53+        full_key = self.cache.make_key('val')
54+        exp = self.cache._expire_info[full_key]
55+        self.cache.incr('val')
56+        exp2 = self.cache._expire_info[full_key]
57+        self.assertEqual(exp, exp2)
58+               
59 
60 # memcached backend isn't guaranteed to be available.
61 # To check the memcached backend, the test settings file will