Ticket #12399: memcached-timeout-fixes-with-tests-r12394.diff
File memcached-timeout-fixes-with-tests-r12394.diff, 2.9 KB (added by , 15 years ago) |
---|
-
django/core/cache/backends/memcached.py
1 1 "Memcached cache backend" 2 2 3 import time 4 3 5 from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError 4 6 from django.utils.encoding import smart_unicode, smart_str 5 7 … … 16 18 BaseCache.__init__(self, params) 17 19 self._cache = memcache.Client(server.split(';')) 18 20 21 def _get_memcache_timeout(self, timeout): 22 """ 23 Memcached deals with long (> 30 days) timeouts in a special 24 way. Call this function to obtain a safe value for your timeout. 25 """ 26 timeout = timeout or self.default_timeout 27 if timeout > 2592000: # 60*60*24*30, 30 days 28 # See http://code.google.com/p/memcached/wiki/FAQ 29 # "You can set expire times up to 30 days in the future. After that 30 # memcached interprets it as a date, and will expire the item after 31 # said date. This is a simple (but obscure) mechanic." 32 # 33 # This means that we have to switch to absolute timestamps. 34 timeout += int(time.time()) 35 return timeout 36 19 37 def add(self, key, value, timeout=0): 20 38 if isinstance(value, unicode): 21 39 value = value.encode('utf-8') 22 return self._cache.add(smart_str(key), value, timeout or self.default_timeout)40 return self._cache.add(smart_str(key), value, self._get_memcache_timeout(timeout)) 23 41 24 42 def get(self, key, default=None): 25 43 val = self._cache.get(smart_str(key)) … … 34 52 def set(self, key, value, timeout=0): 35 53 if isinstance(value, unicode): 36 54 value = value.encode('utf-8') 37 self._cache.set(smart_str(key), value, timeout or self.default_timeout)55 self._cache.set(smart_str(key), value, self._get_memcache_timeout(timeout)) 38 56 39 57 def delete(self, key): 40 58 self._cache.delete(smart_str(key)) -
tests/regressiontests/cache/tests.py
347 347 def setUp(self): 348 348 self.cache = get_cache(settings.CACHE_BACKEND) 349 349 350 def test_long_timeout(self): 351 ''' 352 Using a timeout greater than 30 days makes memcached think 353 it is an absolute expiration timestamp instead of a relative 354 offset. Test that we honour this convention. Refs #12399. 355 ''' 356 self.cache.set('key1', 'eggs', 60*60*24*30 + 1) #30 days + 1 second 357 self.assert_('key1' in self.cache) 358 350 359 class FileBasedCacheTests(unittest.TestCase, BaseCacheTests): 351 360 """ 352 361 Specific test cases for the file-based cache.