gpt4 book ai didi

python - django-tenant-schemas : How to use with single tenant/without subdomains

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:16 28 4
gpt4 key购买 nike

我开始在我的项目中使用 django-tenant-schemas,所有数据表(用户等)完全分离。

我的要求是我可以在私有(private)服务器上为单个客户部署相同的代码库,也可以在云上为多个客户部署相同的代码库。 django-tenant-schemas 的路由不支持。如果我只有一个租户,它仍然需要一个用于数据库路由的子域。

对于使用 runserver 的本地主机开发,我现在需要在我的/etc/hosts 中添加一行以使其工作,例如:

127.0.0.1       testtenant.localhost.com

我怎样才能解决这个问题?

最佳答案

这个自定义中间件扩展了原始的 django-tenant-schemas,检查是否只有一个租户模式存在并设置请求数据库连接到它。这样您就可以简单地创建一个租户并继续使用例如localhost:8000 用于您的开发工作以及为单个租户托管它。

from django.db import connection
from django.contrib.contenttypes.models import ContentType
from tenant_schemas.middleware import TenantMiddleware
from tenant_schemas.utils import get_tenant_model, get_public_schema_name


def get_tenant_schemas():
''' Return all tenant schemas '''
return get_tenant_model().objects.exclude(
schema_name=get_public_schema_name())


class SchemaRouterMiddleware(TenantMiddleware):
"""
Extends the original routing middleware from django-tenant-schemas.
To support both types of deployment (cloud with many tenants vs. single
tenant on own server) we check if our database holds more than one tenant:
- Yes: Select schema based on subdomain (= django-tenant-schemas default)
- No: Always use that single tenant's schema no matter what the
incoming host name is (ip, domain, subdomain, ...)
"""
single_tenant = False

def __init__(self):
'''
Adding a new tenant will most likely go with a server restart so we can
avoid querying the table with each request and only do this once here:
'''
tenants = get_tenant_schemas()
if tenants.count() == 1:
self.single_tenant = tenants[0]

def process_request(self, request):
if self.single_tenant:
connection.set_tenant(self.single_tenant)
request.tenant = self.single_tenant
ContentType.objects.clear_cache()
else:
super(SchemaRouterMiddleware, self).process_request(request)

设置自定义中间件而不是原来的中间件:

MIDDLEWARE_CLASSES = ( 
'middleware.apps.schemas.router.SchemaRouterMiddleware',
...
)

关于python - django-tenant-schemas : How to use with single tenant/without subdomains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28667176/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com