简体   繁体   中英

Using Django tenants on the same domain, rather than subdomains or multiple domains

If I am using django-tenant-schemas (or django-tenants fork), the way they appear to be set up is that you would access the tenants on a separate subdomain or separate domain.

This means accessing tenant1 using tenant1.mysite.com or tenant1.com.

However, I would like to access tenants using mysite.com/tenant1/, mysite.com/tenant2/.

This is because I am using DRF, and so I just want their information stored separately. And I want to access them via the API in the same way. So, for instance I can make calls to mysite.com/tenant1/api/token/.

How would I set this up?

You can use a custom middleware then substitute the default middleware with it. Advanced usage section of Django Tenant Schema documentation (which, i guess, is also the same in Django Tenants) described how to do that. Below is an example of how to use custom HTTP Headers.

class XHeaderTenantMiddleware(BaseTenantMiddleware):
"""
Determines tenant by the value of the ``X-DTS-SCHEMA`` HTTP header.
"""
def get_tenant(self, model, hostname, request):
    schema_name = request.META.get('HTTP_X_DTS_SCHEMA', get_public_schema_name())
    return model.objects.get(schema_name=schema_name)

In your case, instead of using HTTP Header you can get your tenants by extracting them from the URL path (maybe using string.split("delimiter")) then you set that as the value of the schema_name in the code above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM