summaryrefslogtreecommitdiff
path: root/django/core/cache/backends/base.py
diff options
context:
space:
mode:
authorBerker Peksag <berker.peksag@gmail.com>2014-11-23 20:33:07 +0200
committerBerker Peksag <berker.peksag@gmail.com>2015-03-14 20:07:16 +0200
commit34fb909180e9df06fa6a993dd5696a49cd152a0b (patch)
tree58dc89a71e6579ebfcb4abed5fc7a8c0c2b0b023 /django/core/cache/backends/base.py
parenta52cd407b86a51e1badf6771e590361e24fd7155 (diff)
Fixed #12982 -- Added a get_or_set() method to the BaseCache backend.
Diffstat (limited to 'django/core/cache/backends/base.py')
-rw-r--r--django/core/cache/backends/base.py21
1 files changed, 21 insertions, 0 deletions
diff --git a/django/core/cache/backends/base.py b/django/core/cache/backends/base.py
index 7ac1e5bc32..26113aaa31 100644
--- a/django/core/cache/backends/base.py
+++ b/django/core/cache/backends/base.py
@@ -147,6 +147,27 @@ class BaseCache(object):
d[k] = val
return d
+ def get_or_set(self, key, default=None, timeout=DEFAULT_TIMEOUT, version=None):
+ """
+ Fetch a given key from the cache. If the key does not exist,
+ the key is added and set to the default value. The default value can
+ also be any callable. If timeout is given, that timeout will be used
+ for the key; otherwise the default cache timeout will be used.
+
+ Returns the value of the key stored or retrieved on success,
+ False on error.
+ """
+ if default is None:
+ raise ValueError('You need to specify a value.')
+ val = self.get(key, version=version)
+ if val is None:
+ if callable(default):
+ default = default()
+ val = self.add(key, default, timeout=timeout, version=version)
+ if val:
+ return self.get(key, version=version)
+ return val
+
def has_key(self, key, version=None):
"""
Returns True if the key is in the cache and has not expired.