0001-multitenant-add-delete_tenant-command-15513.patch
hobo/multitenant/management/commands/delete_tenant.py | ||
---|---|---|
1 |
import sys |
|
2 |
from optparse import make_option |
|
3 | ||
4 |
from django.core.management.base import CommandError, BaseCommand |
|
5 |
from hobo.multitenant.middleware import TenantMiddleware |
|
6 | ||
7 | ||
8 |
class Command(BaseCommand): |
|
9 |
help = "Delete tenant(s) by hostname(s)" |
|
10 |
args = ['...'] |
|
11 |
option_list = BaseCommand.option_list + ( |
|
12 |
make_option('--force-drop', action='store_true', default=False, |
|
13 |
help='If you want the schema to be deleted from database'), |
|
14 |
) |
|
15 | ||
16 |
def handle(self, *args, **options): |
|
17 | ||
18 |
if not args: |
|
19 |
raise CommandError("you must give at least one tenant hostname") |
|
20 | ||
21 |
# if - is given on the command line, get list of hostnames from stdin |
|
22 |
if '-' in args: |
|
23 |
args = list(args) |
|
24 |
args.remove('-') |
|
25 |
args.extend([x.strip() for x in sys.stdin.readlines()]) |
|
26 |
for hostname in args: |
|
27 |
tenant = TenantMiddleware.get_tenant_by_hostname(hostname) |
|
28 |
tenant.delete(force_drop=options['force_drop']) |
|
29 |
hobo/multitenant/models.py | ||
---|---|---|
1 | 1 |
import os |
2 | 2 |
from urlparse import urljoin |
3 | 3 |
import json |
4 |
from shutil import rmtree |
|
4 | 5 | |
5 | 6 |
from django.conf import settings |
6 | 7 |
from django.db import connection |
8 |
from django.utils import timezone |
|
7 | 9 | |
8 | 10 |
from tenant_schemas.utils import get_public_schema_name |
9 | 11 |
from tenant_schemas.models import TenantMixin |
... | ... | |
65 | 67 |
"the public schema. Current schema is %s." |
66 | 68 |
% connection.schema_name) |
67 | 69 | |
68 |
os.rename(self.get_directory(), self.get_directory() + '.invalid') |
|
70 |
delete_date = timezone.now().strftime('%Y%m%d%H%M%S%f') |
|
71 |
if force_drop: |
|
72 |
rmtree(self.get_directory()) |
|
73 |
else: |
|
74 |
os.rename(self.get_directory(), self.get_directory() + '.removed_%s.invalid' % delete_date) |
|
75 | ||
76 |
if schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop): |
|
77 |
cursor = connection.cursor() |
|
78 |
cursor.execute('DROP SCHEMA %s CASCADE' % self.schema_name) |
|
79 | ||
80 |
if schema_exists(self.schema_name) and (not self.auto_drop_schema and not force_drop): |
|
81 |
cursor = connection.cursor() |
|
82 |
cursor.execute('ALTER SCHEMA %s RENAME TO removed_%s_%s' % (self.schema_name, delete_date, self.schema_name)) |
|
69 | 83 | |
70 |
if schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop): |
|
71 |
cursor = connection.cursor() |
|
72 |
cursor.execute('DROP SCHEMA %s CASCADE' % self.schema_name) |
|
73 |
- |