z_cache

privex.helpers.cache.extras.z_cache(cls: Union[CacheManagerMixin, Type[CacheManagerMixin]] = None, cache_key: Union[str, callable] = None, cache_time=<class 'privex.helpers.types.AutoDetected'>, format_args: list = None, format_opt: privex.helpers.decorators.FormatOpt = <FormatOpt.POS_AUTO: 'force_pos'>, extract_class=True, **opts)[source]

A special method caching decorator which is designed to integrate with classes that extend CacheManagerMixin

This is simply a wrapper for r_cache() - it transparently caches the output of a wrapped method/function, but unlike r_cache(), it’s designed to automatically integrate with classes which extend CacheManagerMixin , allowing it to automatically retrieve cache settings such as the cache prefix, default cache time, along with directly calling various classmethods which enable logging of newly created cache_key ‘s for painless cleanup of cache keys when needed, without having to manually track them, or doing the nuclear option of erasing the entire cache system’s database.

It integrates with your class by intercepting the first argument of any method calls that are wrapped with z_cache(). Both standard instance methods and classmethod ‘s are supported transparently - while static methods will only integrate properly with your own class if you set cls (first argument) on the decorator to point to the class or instance containing your cache manager settings and inherited methods from CacheManagerMixin

After you’ve extended CacheManagerMixin, you can enable argument-based caching for any method, simply by adding the decorator line @z_cache() above it. z_cache() will automatically handle the cache key name, including extracting your method’s passed arguments and inserting them into the cache key, ensuring method calls with certain arguments, are cached separately from other method calls with a different set of arguments.

Example:

>>> from privex.helpers.cache.extras import CacheManagerMixin, z_cache
>>> from time import sleep
>>>
>>> class MyClass(CacheManagerMixin):
...     # It's recommended, but not necessary - to re-create cache_key_lock with None, as it will ensure your
...     # class has a separate threading.Lock() instance from other CacheManagerMixin based classes
...     cache_key_lock: Optional[threading.Lock] = None
...     # You should override cache_prefix to ensure cache keys auto-created for your class won't
...     # conflict with cache keys created by other classes
...     cache_prefix: str = 'my_class'
...     # While it's possible to set the cache timeout per method with z_cache / per call to cache_set,
...     # it's helpful to adjust default_cache_time to a number of seconds which is suitable for most
...     # methods in your class, avoiding the need to specify it each time..
...     default_cache_time: Union[float, int] = 300
...     # default_cache_key_time should generally be set to the same number of seconds as default_cache_time.
...     # It controls how long the "cache key log" is held for, which is simply a list of known cache keys for
...     # your class, enabling the use of the method .clear_all_cache_keys
...     default_cache_key_time: Union[float, int] = 300
...
...     @z_cache()
...     def hello(self, world=10):
...         sleep(5)
...         return f"Hello world: {world}"
...
>>> c = MyClass()
>>> # The first call to hello() will take 5 seconds due to the sleep
>>> c.hello()
Hello world: 10
>>> c.hello()   # But when we call it again - it returns instantly
Hello world: 10
>>> # If we call .hello() with a different set of arguments, it will result in a new cache key being auto-generated,
>>> # requiring a new, non-cached call to hello() to get the result for '5'
>>> c.hello(5)
Hello world: 5
Parameters
  • cls (CACHE_MGR) – For functions or methods which don’t have a CacheManagerMixin based class or instance being passed as their first argument, you’ll need to set cls to point to a CacheManagerMixin based class or instance, so that z_cache() is able to both retrieve your overridden cache settings, and call the various helper classmethod’s for handling prefixed cache keys etc.

  • cache_key (str|callable) –

    If you don’t like automatic determination and argument-based generation of the cache_key, you may manually set the cache key to store the output of the method into.

    For dynamic generation of the cache key, this may be set to a callable, such as a lambda, function, or method which returns the cache key to be used as a str. However, whatever callable is passed, must accept the exact same positional and keyword arguments as the method being wrapped - as those will be the args/kwargs passed to your cache_key callable object.

  • cache_time (float|int) – The number of seconds to cache the output of the wrapped method/function for. By default, this is automatically extracted from the class of the wrapped function, by retrieving default_cache_time

  • format_args – See the docs for r_cache()

  • format_opt – See the docs for r_cache()

  • extract_class (bool) –

    (Default: True) This argument controls whether or not we attempt to auto-extract the related class/instance of the wrapped method by analyzing the first positional argument, along with the keyword arguments self and cls if they’re present.

    If extract_class is set to False, no attempt will be made to retrieve the related class/instance using the first argument - instead, if cls isn’t passed, it will immediately fall back to using the original parent class for settings - CacheManagerMixin

  • opts – See the docs for r_cache()

Returns