Skip to content

Commit

Permalink
Fix inconsistency between cache for timeout = None or 0.
Browse files Browse the repository at this point in the history
timeout = 0 or timeout = None will now behave as "never expires" everywhere
  • Loading branch information
Kyria committed Dec 24, 2017
1 parent e984656 commit 0ab29b0
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions esipy/cache.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
# -*- encoding: utf-8 -*-
""" Cache objects for EsiPy """
import hashlib
import logging
import time

try:
import pickle
except ImportError: # pragma: no cover
import cPickle as pickle

import logging

LOGGER = logging.getLogger(__name__)


def _hash(data):
""" generate a hash from data object to be used as cache key """
hash_algo = hashlib.new('md5')
hash_algo.update(pickle.dumps(data))
# prefix allows possibility of multiple applications
Expand All @@ -27,7 +27,7 @@ class BaseCache(object):
"""

def set(self, key, value, timeout=300):
""" Set a value in the cache """
""" Set a value in the cache. If timeout=(None): never expires """
raise NotImplementedError

def get(self, key, default=None):
Expand Down Expand Up @@ -65,7 +65,8 @@ def __del__(self):
self._cache.close()

def set(self, key, value, timeout=300):
self._cache.set(_hash(key), value, expire=timeout)
expire_time = None if timeout == 0 else timeout
self._cache.set(_hash(key), value, expire=expire_time)

def get(self, key, default=None):
return self._cache.get(_hash(key), default)
Expand All @@ -89,7 +90,10 @@ def get(self, key, default=None):
return cache_val[0]

def set(self, key, value, timeout=300):
expire_time = None if timeout is None else timeout + time.time()
if timeout is None or timeout == 0:
expire_time = None
else:
expire_time = timeout + time.time()
self._dict[key] = (value, expire_time)

def invalidate(self, key):
Expand Down Expand Up @@ -133,7 +137,7 @@ def get(self, key, default=None):
return value if value is not None else default

def set(self, key, value, timeout=300):
expire_time = 0 if timeout is None else timeout + time.time()
expire_time = 0 if timeout is None else timeout
return self._mc.set(_hash(key), value, expire_time)

def invalidate(self, key):
Expand All @@ -159,6 +163,8 @@ def get(self, key, default=None):
return pickle.loads(value) if value is not None else default

def set(self, key, value, timeout=300):
if timeout is None or timeout == 0:
return self._r.set(_hash(key), pickle.dumps(value))
return self._r.setex(_hash(key), pickle.dumps(value), timeout)

def invalidate(self, key):
Expand Down

0 comments on commit 0ab29b0

Please sign in to comment.