Ticket #12982: get_or_set.diff
File get_or_set.diff, 2.7 KB (added by , 14 years ago) |
---|
-
docs/topics/cache.txt
731 731 732 732 Like ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter. 733 733 734 In cases where you may wish to use either a cached value or create a new cached value 735 there is the ``get_or_set()`` method. It takes the same parameters as get but rather than simply return 736 the default value, the default is set as the new cache value for that key. If the default value is callable 737 it's return value will be stored. 738 739 >>> cache.get_or_set('a',1) 740 >>> cache.get('a') 741 1 742 >>> cache.set('b',1) 743 >>> cache.get_or_set('b',2) 744 1 745 734 746 You can delete keys explicitly with ``delete()``. This is an easy way of 735 747 clearing the cache for a particular object:: 736 748 -
django/core/cache/backends/base.py
125 125 if val is not None: 126 126 d[k] = val 127 127 return d 128 129 def get_or_set(self,key,default,**kwargs): 130 """ 131 Fetch a given key from the cache. If the key does not exist, the default value is used. 132 If the default value is callable the key will be set to it's return value. 133 """ 134 val = self.get(key,**kwargs) 135 if val is None: 136 if callable(default): 137 val = default() 138 else: 139 val = default 140 self.add(key,val,**kwargs) 141 return val 142 128 143 129 144 def has_key(self, key, version=None): 130 145 """ -
tests/regressiontests/cache/tests.py
202 202 self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'}) 203 203 self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'}) 204 204 205 def test_get_or_set(self): 206 #Test when no value is set 207 self.cache.get_or_set('a','a') 208 self.assertEqual(self.cache.get('a'),'a') 209 210 #Test an existing value 211 self.cache.set('b','b') 212 self.assertEqual(self.cache.get_or_set('b','c'),'b') 213 214 #Test a callable 215 def cache_val(): 216 return 'c' 217 218 self.cache.get_or_set('c',cache_val) 219 self.assertEqual(self.cache.get('c'),'c') 220 205 221 def test_delete(self): 206 222 # Cache keys can be deleted 207 223 self.cache.set("key1", "spam")