Lazy Cache
Django’s cache, imported only once Django is ready.
Importing django.core.cache while Django is still starting can leave it on
an unexpected backend, such as a local-memory cache that silently persists
nothing: sessions are lost, and cached results are recomputed in every
process. lazy_cache has the api of django.core.cache.cache, and
imports it only on first use, once Django’s apps are ready.
from cache_results import lazy_cache as cache
cache.set("my_key", "my_value", timeout=300)
cache.get("my_key") # "my_value"
On first use it also checks the cache: it writes and reads a test key, and
warns when the default cache is a local-memory or dummy backend, which is
usually a misconfiguration in production.
- class cache_results.lazy.LazyCache[source]
Bases:
objectDjango’s default cache, imported on first use.
Use the module’s
lazy_cacheinstance. Every method passes its arguments to the method of the same name ofdjango.core.cache.cache.- property ready: bool
Whether the cache can be used yet: True once Django’s apps are ready.
Until then,
cachereturnsNonerather than initialize Django’s cache prematurely, so callers that may run during startup check this first, as@cache_resultsdoes.- Return type:
- property cache
Import and return
django.core.cache.cache, checking it on first use.- Returns:
The cache, or
Nonebefore Django’s apps are ready.- Return type:
Optional[django.core.cache.backends.base.BaseCache]
- set(key, value, timeout=<object object>, version=None)[source]
Set a value.
Without
timeout, the cache’s own timeout is used, andNonenever expires.
- add(key, value, timeout=<object object>, version=None) bool[source]
Set a value only if the key is not cached yet.
- cache_results.lazy.lazy_cache = <cache_results.lazy.LazyCache object>
Django’s default cache, imported on first use, with the api of
django.core.cache.cache.