Fetch a given key from the cache. If the key does not exist, add the key and set it to the default value. The default value can also be any callable. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. Return the value
(self, key, default, timeout=DEFAULT_TIMEOUT, version=None)
| 220 | return d |
| 221 | |
| 222 | def get_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None): |
| 223 | """ |
| 224 | Fetch a given key from the cache. If the key does not exist, |
| 225 | add the key and set it to the default value. The default value can |
| 226 | also be any callable. If timeout is given, use that timeout for the |
| 227 | key; otherwise use the default cache timeout. |
| 228 | |
| 229 | Return the value of the key stored or retrieved. |
| 230 | """ |
| 231 | val = self.get(key, self._missing_key, version=version) |
| 232 | if val is self._missing_key: |
| 233 | if callable(default): |
| 234 | default = default() |
| 235 | self.add(key, default, timeout=timeout, version=version) |
| 236 | # Fetch the value again to avoid a race condition if another caller |
| 237 | # added a value between the first get() and the add() above. |
| 238 | return self.get(key, default, version=version) |
| 239 | return val |
| 240 | |
| 241 | async def aget_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None): |
| 242 | """See get_or_set().""" |