get_or_set

privex.helpers.cache.get_or_set(key: str, value: Union[Any, callable], timeout: int = 300) → Any[source]

Attempt to return the value of key in the cache. If key doesn’t exist or is expired, then it will be set to value, and value will be returned.

The value parameter can be any standard type such as str or dict - or it can be a callable function / method which returns the value to set and return.

Basic Usage:

>>> from privex.helpers import cache as c
>>> c.get('testing')
None
>>> c.get_or_set('testing', 'hello world')
'hello world'
>>> c.get('testing')
'hello world'

Set and get the value from a function if ``key`` didn’t exist / was expired:

>>> def my_func(): return "hello world"
>>> c.get_or_set('example', my_func)
'hello world'
>>> c.get('example')
'hello world'
Parameters
  • key (str) – The cache key (as a string) to get/set the value for, e.g. example:test

  • value (Any) – The value to store in the cache key key. Can be a standard type, or a callable function.

  • timeout (int) – The amount of seconds to keep the data in cache. Pass None to disable expiration.

Return Any value

The value of the cache key key, or value if it wasn’t found.