[1.7.x] Fixed #22606 -- Locmemcache has_key() failed for infinite cache expiry

Refactored cache expiry logic for Locmemcache to make consistent across
all places where accessed, and correctly handle None as expiry time.
Backport of 66880e4cd from master.
This commit is contained in:
Malcolm Box 2014-05-09 11:23:28 +01:00 committed by Claude Paroz
parent 31eac71a76
commit 8a090c21f1
2 changed files with 11 additions and 8 deletions

View File

@ -29,8 +29,7 @@ class LocMemCache(BaseCache):
self.validate_key(key) self.validate_key(key)
pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
with self._lock.writer(): with self._lock.writer():
exp = self._expire_info.get(key, 0) if self._has_expired(key):
if exp is not None and exp <= time.time():
self._set(key, pickled, timeout) self._set(key, pickled, timeout)
return True return True
return False return False
@ -40,8 +39,7 @@ class LocMemCache(BaseCache):
self.validate_key(key) self.validate_key(key)
pickled = None pickled = None
with self._lock.reader(): with self._lock.reader():
exp = self._expire_info.get(key, 0) if not self._has_expired(key):
if exp is None or exp > time.time():
pickled = self._cache[key] pickled = self._cache[key]
if pickled is not None: if pickled is not None:
try: try:
@ -85,10 +83,7 @@ class LocMemCache(BaseCache):
key = self.make_key(key, version=version) key = self.make_key(key, version=version)
self.validate_key(key) self.validate_key(key)
with self._lock.reader(): with self._lock.reader():
exp = self._expire_info.get(key) if not self._has_expired(key):
if exp is None:
return False
elif exp > time.time():
return True return True
with self._lock.writer(): with self._lock.writer():
@ -99,6 +94,12 @@ class LocMemCache(BaseCache):
pass pass
return False return False
def _has_expired(self, key):
exp = self._expire_info.get(key, -1)
if exp is None or exp > time.time():
return False
return True
def _cull(self): def _cull(self):
if self._cull_frequency == 0: if self._cull_frequency == 0:
self.clear() self.clear()

View File

@ -286,6 +286,8 @@ class BaseCacheTests(object):
cache.set("hello1", "goodbye1") cache.set("hello1", "goodbye1")
self.assertEqual(cache.has_key("hello1"), True) self.assertEqual(cache.has_key("hello1"), True)
self.assertEqual(cache.has_key("goodbye1"), False) self.assertEqual(cache.has_key("goodbye1"), False)
cache.set("no_expiry", "here", None)
self.assertEqual(cache.has_key("no_expiry"), True)
def test_in(self): def test_in(self):
# The in operator can be used to inspect cache contents # The in operator can be used to inspect cache contents