django-constance icon indicating copy to clipboard operation
django-constance copied to clipboard

Making CONSTANCE_DATABASE_CACHE_BACKEND tenant aware

Open nv0284 opened this issue 2 years ago • 2 comments

Describe the problem

I have added constance in my TENANT_APPS that will create constance tables for each tenant in db. But in case of caching, the redis is shared between tenants. How can I make the caching of constance config tenant aware?

nv0284 avatar May 16 '22 13:05 nv0284

What exactly tenant library do you use? You can use database backend and it should work out of box. May be this option for cache help backend https://docs.djangoproject.com/en/4.1/ref/settings/#std-setting-CACHES-KEY_PREFIX

sergei-iurchenko avatar Mar 15 '23 23:03 sergei-iurchenko

I had similar issue with django-tenants. The database worked perfectly as connection hits the constance_config table in correct schema for tenant. However when I cache in Redis it has key collision. As tenants share an instance of django KEY_PREFIX doesn't not solve issue. I worked around with the following and pointed CONSTANCE_BACKEND at this class.

from constance.backends.database import DatabaseBackend
from django.db import connection

class ConstanceTenantDatabaseBackend(DatabaseBackend):
    def add_prefix(self, key):
        tenant = connection.tenant
        return "%s:%s:%s" % (tenant.schema_name, self._prefix, key)

welliot avatar Jul 23 '23 23:07 welliot