Ticket #12982: get_or_set.diff

File get_or_set.diff, 2.7 KB (added by James Snow, 13 years ago)
  • docs/topics/cache.txt

     
    731731
    732732Like ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter.
    733733
     734In cases where you may wish to use either a cached value or create a new cached value
     735there is the ``get_or_set()`` method. It takes the same parameters as get but rather than simply return
     736the default value, the default is set as the new cache value for that key. If the default value is callable
     737it'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
    734746You can delete keys explicitly with ``delete()``. This is an easy way of
    735747clearing the cache for a particular object::
    736748
  • django/core/cache/backends/base.py

     
    125125            if val is not None:
    126126                d[k] = val
    127127        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                 
    128143
    129144    def has_key(self, key, version=None):
    130145        """
  • tests/regressiontests/cache/tests.py

     
    202202        self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'})
    203203        self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'})
    204204
     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       
    205221    def test_delete(self):
    206222        # Cache keys can be deleted
    207223        self.cache.set("key1", "spam")
Back to Top