hobo/hobo/multitenant/cache.py

39 lines
1.4 KiB
Python

from django.core.cache.backends.base import InvalidCacheBackendError
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.utils.module_loading import import_string
class TenantBaseCache:
'''Prepend the tenant schema name to the cache prefix'''
def set_key_prefix(self, prefix):
self.__key_prefix = prefix
def get_key_prefix(self):
if connection.tenant:
return '%s_%s' % (connection.tenant.schema_name, self.__key_prefix)
return self.__key_prefix
key_prefix = property(get_key_prefix, set_key_prefix)
__DERIVED_CLASSES = {}
def TenantCache(host, params, **kwargs):
try:
backend = params['REAL_BACKEND']
except KeyError:
raise ImproperlyConfigured('The %s.TenantCache backend needs a REAL_BACKEND parameter' % __name__)
try:
backend_cls = import_string(backend)
except ImportError as e:
raise InvalidCacheBackendError("Could not find backend '%s': %s" % (backend, e))
derived_cls_name = 'Tenant' + backend_cls.__name__
if derived_cls_name not in __DERIVED_CLASSES:
# dynamically create a new class with TenantBaseCache
# and the original class as parents
__DERIVED_CLASSES[derived_cls_name] = type(derived_cls_name, (TenantBaseCache, backend_cls), {})
return __DERIVED_CLASSES[derived_cls_name](host, params, **kwargs)