diff --git a/django/core/cache/backends/locmem.py b/django/core/cache/backends/locmem.py index 1fa17052fd..245c170bb4 100644 --- a/django/core/cache/backends/locmem.py +++ b/django/core/cache/backends/locmem.py @@ -26,28 +26,31 @@ class LocMemCache(BaseCache): def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) + try: + pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) + except pickle.PickleError: + return False with self._lock.writer(): exp = self._expire_info.get(key) if exp is None or exp <= time.time(): - try: - pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) - self._set(key, pickled, timeout) - return True - except pickle.PickleError: - pass + self._set(key, pickled, timeout) + return True return False def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) + pickled = None with self._lock.reader(): exp = self._expire_info.get(key, 0) if exp is None or exp > time.time(): - try: - pickled = self._cache[key] - return pickle.loads(pickled) - except pickle.PickleError: - return default + pickled = self._cache[key] + try: + if pickled is not None: + return pickle.loads(pickled) + except pickle.PickleError: + return default + with self._lock.writer(): try: del self._cache[key] @@ -68,25 +71,25 @@ class LocMemCache(BaseCache): def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_key(key, version=version) self.validate_key(key) - with self._lock.writer(): - try: - pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) + try: + pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) + with self._lock.writer(): self._set(key, pickled, timeout) - except pickle.PickleError: - pass - + except pickle.PickleError: + pass + def incr(self, key, delta=1, version=None): value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta key = self.make_key(key, version=version) - with self._lock.writer(): - try: - pickled = pickle.dumps(new_value, pickle.HIGHEST_PROTOCOL) + try: + pickled = pickle.dumps(new_value, pickle.HIGHEST_PROTOCOL) + with self._lock.writer(): self._cache[key] = pickled - except pickle.PickleError: - pass + except pickle.PickleError: + pass return new_value def has_key(self, key, version=None):