Source code for ferrosoft.apps.ferrobase.management.tenantcommand
import sys
from django.core.management import BaseCommand
from ferrosoft.apps.ferrobase.models import Tenant
from ferrosoft.apps.ferrobase.tenant.context import active_tenant
[docs]
class TenantAwareCommand(BaseCommand):
"""Base class for management commands that operate on a single tenant database.
Adds a ``-T / --tenant`` argument. When a tenant name is supplied, the
tenant database connection is activated and ``handle_tenant`` is called
inside that context. Without a tenant name the master database is used and
a warning is printed to stderr.
Subclasses must implement ``handle_tenant``.
"""
tenant: Tenant | None = None
[docs]
def add_arguments(self, parser):
parser.add_argument(
"-T",
"--tenant",
type=str,
help="Tenant name",
)
[docs]
def handle(self, *args, **options):
tenant_name = options["tenant"]
if not tenant_name:
self.stderr.write(self.style.WARNING("Using master database"))
return self.handle_tenant(*args, **options)
with active_tenant(Tenant.lookup(tenant_name)) as tenant:
if tenant is None:
self.stderr.write("Tenant not found: %s" % tenant_name)
sys.exit(1)
self.tenant = tenant
return self.handle_tenant(*args, **options)
[docs]
def handle_tenant(self, *args, **options):
"""Execute command logic for the active tenant context.
Called by ``handle`` after activating the tenant database connection.
``self.tenant`` holds the active ``Tenant`` instance (or ``None`` when
running against the master database).
Args:
*args: Positional arguments forwarded from the CLI parser.
**options: Keyword arguments forwarded from the CLI parser.
"""
raise NotImplementedError()