diff --git a/hobo/multitenant/middleware.py b/hobo/multitenant/middleware.py index 903d9c0..a855545 100644 --- a/hobo/multitenant/middleware.py +++ b/hobo/multitenant/middleware.py @@ -1,6 +1,8 @@ import os import glob +import hashlib +from django.utils.encoding import smart_bytes from django.conf import settings from django.db import connection from django.http import Http404, HttpResponseRedirect @@ -27,7 +29,11 @@ class TenantMiddleware(object): '''Convert hostname to PostgreSQL schema name''' if hostname in getattr(settings, 'TENANT_MAPPING', {}): return settings.TENANT_MAPPING[hostname] - return hostname.replace('.', '_').replace('-', '_') + schema = hostname.replace('.', '_').replace('-', '_') + if len(schema) > 63: + digest = hashlib.md5(smart_bytes(schema)).hexdigest()[:4] + schema = '%s_%s_%s' % (schema[:29], digest, schema[-28:]) + return schema @classmethod def get_tenant_by_hostname(cls, hostname): diff --git a/tests_multitenant/test_middleware.py b/tests_multitenant/test_middleware.py new file mode 100644 index 0000000..eabbbaa --- /dev/null +++ b/tests_multitenant/test_middleware.py @@ -0,0 +1,15 @@ +from hobo.multitenant.middleware import TenantMiddleware + + +def test_hostname2schema(): + assert TenantMiddleware.hostname2schema('x' * 63) == ('x' * 63) + shortened = TenantMiddleware.hostname2schema('x' * 64) + # no more than 63 characters + assert len(shortened) == 63 + # it's different than just the 63 first characters + assert shortened != ('x' * 63) + # but it matches the prefix + assert shortened[:20] == ('x' * 20) + # and it matches the suffix + assert shortened[-20:] == ('x' * 20) +