Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Last active May 20, 2022 08:16
Show Gist options
  • Save wonderbeyond/b6e2b45224ec9bcaf1bd53d2b00c63aa to your computer and use it in GitHub Desktop.
Save wonderbeyond/b6e2b45224ec9bcaf1bd53d2b00c63aa to your computer and use it in GitHub Desktop.
[Python] Multiple-backend caches management
from typing import Any, Type
from xxx.utils import import_from_string
from xxx.conf import get_settings
undefined = object()
CACHE_BACKENDS = {
'fs': 'cachelib.file.FileSystemCache',
'memory': 'cachelib.simple.SimpleCache',
'redis': 'cachelib.redis.RedisCache',
}
_named_caches: dict[str, Any] = {}
def get_cache(name='default'):
cache_params = gs(f'caches.{name}', undefined)
if name in _named_caches:
return _named_caches[name]
if cache_params is undefined:
raise ValueError(f'settings of cache "{name}" not found.')
if (backend_name := cache_params['backend']) not in CACHE_BACKENDS:
raise ValueError(f'Unknown cache backend "{backend_name}"')
backend_cls: Type | str = CACHE_BACKENDS[backend_name]
cache_cls = import_from_string(backend_cls) if isinstance(backend_cls, str) else backend_cls
cache = cache_cls(**{
k: v for k, v in cache_params.items()
if k != 'backend' and v is not None
})
_named_caches[name] = cache
return cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment