Smarter Lazy Cache

smarter.lib.cache.lazy_cache

This module provides a lazy wrapper around Django’s cache framework, ensuring safe and reliable cache access in the Smarter framework.

Key Features:

  • Defines the LazyCache class, which defers importing Django’s cache until first use to avoid premature initialization issues.

  • Exports a singleton instance lazy_cache with an API identical to django.core.cache.

  • Integrates diagnostics and logging to verify cache backend health and configuration on first access.

  • Supports feature flag management via Django-waffle, with lazy import and enhanced caching for switch checks.

  • Enables verbose and cache activity logging controlled by feature flags and settings.

Usage Example:

from smarter.lib.cache import lazy_cache as cache

cache.set("my_key", "my_value", timeout=300)
value = cache.get("my_key")
print(value)  # Outputs: "my_value"

Notes:

  • Use lazy_cache instead of importing Django’s cache directly to prevent issues where Django falls back to a default, non-persistent cache backend.

  • The lazy_cache instance is intended for use as a singleton throughout the application.

  • See the LazyCache class docstring for more details on features and implementation.

smarter.lib.cache.lazy_cache.lazy_cache = <smarter.lib.cache.lazy_cache.LazyCache object>

A singleton instance of LazyCache for accessing Django’s cache framework without risking premature initialization, which can lead to issues where Django falls back to a default cache backend unexpectedly. When this happens, the fallback cache may not persist data as expected, leading to buggy cache misses such as browser session values not being stored.

# suggest importing like this, in order to clarify
# that you're importing lazy_cache, which has an api
# that is identical to that of django.core.cache
from smarter.lib.cache import lazy_cache as cache

cache.set("my_key", "my_value", timeout=300)
value = cache.get("my_key")
print(value)  # Outputs: "my_value"