Django

Code

Ticket #4831: 4831-1.diff

File 4831-1.diff, 8.4 kB (added by Matt McClanahan <cardinal@dodds.net>, 1 year ago)
  • django/core/cache/backends/simple.py

    old new  
    2121        except (ValueError, TypeError): 
    2222            self._cull_frequency = 3 
    2323 
     24    def add(self, key, value, timeout=None): 
     25        if len(self._cache) >= self._max_entries: 
     26            self._cull() 
     27        if timeout is None: 
     28            timeout = self.default_timeout 
     29        if key not in self._cache.keys(): 
     30            self._cache[key] = value 
     31            self._expire_info[key] = time.time() + timeout 
     32 
    2433    def get(self, key, default=None): 
    2534        now = time.time() 
    2635        exp = self._expire_info.get(key) 
  • django/core/cache/backends/base.py

    old new  
    1414            timeout = 300 
    1515        self.default_timeout = timeout 
    1616 
     17    def add(self, key, value, timeout=None): 
     18        """ 
     19        Set a value in the cache if the key does not already exist.  If 
     20        timeout is given, that timeout will be used for the key; otherwise 
     21        the default cache timeout will be used. 
     22        """ 
     23        raise NotImplementedError 
     24 
    1725    def get(self, key, default=None): 
    1826        """ 
    1927        Fetch a given key from the cache.  If the key does not exist, return 
  • django/core/cache/backends/dummy.py

    old new  
    66    def __init__(self, *args, **kwargs): 
    77        pass 
    88 
     9    def add(self, *args, **kwargs): 
     10        pass 
     11 
    912    def get(self, key, default=None): 
    1013        return default 
    1114 
  • django/core/cache/backends/locmem.py

    old new  
    99        SimpleCacheClass.__init__(self, host, params) 
    1010        self._lock = RWLock() 
    1111 
     12    def add(self, key, value, timeout=None): 
     13        self._lock.writer_enters() 
     14        try: 
     15            SimpleCacheClass.add(self, key, value, timeout) 
     16        finally: 
     17            self._lock.writer_leaves() 
     18 
    1219    def get(self, key, default=None): 
    1320        should_delete = False 
    1421        self._lock.reader_enters() 
  • django/core/cache/backends/filebased.py

    old new  
    1616        del self._cache 
    1717        del self._expire_info 
    1818 
     19    def add(self, key, value, timeout=None): 
     20        fname = self._key_to_file(key) 
     21        if timeout is None: 
     22            timeout = self.default_timeout 
     23        try: 
     24            filelist = os.listdir(self._dir) 
     25        except (IOError, OSError): 
     26            self._createdir() 
     27            filelist = [] 
     28        if len(filelist) > self._max_entries: 
     29            self._cull(filelist) 
     30        if os.path.basename(fname) not in filelist: 
     31            try: 
     32                f = open(fname, 'wb') 
     33                now = time.time() 
     34                pickle.dump(now + timeout, f, 2) 
     35                pickle.dump(value, f, 2) 
     36            except (IOError, OSError): 
     37                pass 
     38 
    1939    def get(self, key, default=None): 
    2040        fname = self._key_to_file(key) 
    2141        try: 
  • django/core/cache/backends/db.py

    old new  
    2424        except (ValueError, TypeError): 
    2525            self._cull_frequency = 3 
    2626 
     27    def add(self, key, value, timeout=None): 
     28        return self._base_set('add', key, value, timeout) 
     29 
    2730    def get(self, key, default=None): 
    2831        cursor = connection.cursor() 
    2932        cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key = %%s" % self._table, [key]) 
     
    3841        return pickle.loads(base64.decodestring(row[1])) 
    3942 
    4043    def set(self, key, value, timeout=None): 
     44        return self._base_set('set', key, value, timeout) 
     45 
     46    def delete(self, key): 
     47        cursor = connection.cursor() 
     48        cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key]) 
     49        transaction.commit_unless_managed() 
     50 
     51    def has_key(self, key): 
     52        cursor = connection.cursor() 
     53        cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s" % self._table, [key]) 
     54        return cursor.fetchone() is not None 
     55 
     56    def _base_set(self, mode, key, value, timeout=None): 
    4157        if timeout is None: 
    4258            timeout = self.default_timeout 
    4359        cursor = connection.cursor() 
     
    5066        encoded = base64.encodestring(pickle.dumps(value, 2)).strip() 
    5167        cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s" % self._table, [key]) 
    5268        try: 
    53             if cursor.fetchone(): 
     69            if mode == 'set' and cursor.fetchone(): 
    5470                cursor.execute("UPDATE %s SET value = %%s, expires = %%s WHERE cache_key = %%s" % self._table, [encoded, str(exp), key]) 
    5571            else: 
    56                 cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table, [key, encoded, str(exp)]) 
     72                if mode == 'add': 
     73                    cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table, [key, encoded, str(exp)]) 
    5774        except DatabaseError: 
    5875            # To be threadsafe, updates/inserts are allowed to fail silently 
    5976            pass 
    6077        else: 
    6178            transaction.commit_unless_managed() 
    6279 
    63     def delete(self, key): 
    64         cursor = connection.cursor() 
    65         cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key]) 
    66         transaction.commit_unless_managed() 
    67  
    68     def has_key(self, key): 
    69         cursor = connection.cursor() 
    70         cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s" % self._table, [key]) 
    71         return cursor.fetchone() is not None 
    72  
    7380    def _cull(self, cursor, now): 
    7481        if self._cull_frequency == 0: 
    7582            cursor.execute("DELETE FROM %s" % self._table) 
  • django/core/cache/backends/memcached.py

    old new  
    1515        BaseCache.__init__(self, params) 
    1616        self._cache = memcache.Client(server.split(';')) 
    1717 
     18    def add(self, key, value, timeout=0): 
     19        self._cache.add(key.encode('ascii', 'ignore'), value, timeout or self.default_timeout) 
     20 
    1821    def get(self, key, default=None): 
    1922        val = self._cache.get(key) 
    2023        if val is None: 
  • tests/regressiontests/cache/tests.py

    old new  
    1717        cache.set("key", "value") 
    1818        self.assertEqual(cache.get("key"), "value") 
    1919 
     20    def test_add(self): 
     21        # test add (only add if key isn't already in cache) 
     22        cache.add("addkey1", "value") 
     23        cache.add("addkey1", "newvalue") 
     24        self.assertEqual(cache.get("addkey1"), "value") 
     25 
    2026    def test_non_existent(self): 
    2127        # get with non-existent keys 
    2228        self.assertEqual(cache.get("does not exist"), None) 
  • docs/cache.txt

    old new  
    324324    >>> cache.get('my_key', 'has expired') 
    325325    'has expired' 
    326326 
     327To add a key only if it doesn't already exist, there is an add() method.  It 
     328takes the same parameters as set(), but will not attempt to update the cache 
     329if the key specified is already present:: 
     330 
     331    >>> cache.set('add_key', 'Initial value') 
     332    >>> cache.add('add_key', 'New value') 
     333    >>> cache.get('add_key') 
     334    'Initial value' 
     335 
    327336There's also a get_many() interface that only hits the cache once. get_many() 
    328337returns a dictionary with all the keys you asked for that actually exist in the 
    329338cache (and haven't expired)::