16 |
16 |
|
17 |
17 |
import threading
|
18 |
18 |
|
19 |
|
_Thread_bootstrap_inner = threading.Thread._bootstrap_inner
|
20 |
|
_Thread__init__ = threading.Thread.__init__
|
|
19 |
_Thread_start = threading.Thread.start
|
|
20 |
_Thread__bootstrap_inner = threading.Thread._bootstrap_inner
|
21 |
21 |
|
22 |
22 |
|
23 |
|
def _new__init__(self, *args, **kwargs):
|
|
23 |
def _new_start(self):
|
24 |
24 |
from django.db import connection
|
25 |
25 |
|
26 |
|
try:
|
27 |
|
if hasattr(connection, 'get_tenant'):
|
28 |
|
self.tenant = connection.get_tenant()
|
29 |
|
else:
|
30 |
|
self.tenant = None
|
31 |
|
except RuntimeError:
|
32 |
|
# this happens when ImportError is raised at startup; ignore
|
33 |
|
# the error to let the real one be displayed.
|
34 |
|
self.tenant = None
|
35 |
|
_Thread__init__(self, *args, **kwargs)
|
|
26 |
tenant = getattr(connection, 'tenant', None)
|
|
27 |
self.tenant = tenant
|
|
28 |
return _Thread_start(self)
|
36 |
29 |
|
37 |
30 |
|
38 |
|
def _new_bootstrap_inner(self):
|
39 |
|
if self.tenant is not None:
|
|
31 |
def _new__bootstrap_inner(self):
|
|
32 |
tenant = getattr(self, 'tenant', None)
|
|
33 |
|
|
34 |
if tenant is not None:
|
40 |
35 |
from django.db import connection
|
41 |
36 |
|
42 |
37 |
old_tenant = connection.get_tenant()
|
43 |
38 |
connection.set_tenant(self.tenant)
|
44 |
39 |
try:
|
45 |
|
_Thread_bootstrap_inner(self)
|
|
40 |
_Thread__bootstrap_inner(self)
|
46 |
41 |
finally:
|
47 |
42 |
connection.set_tenant(old_tenant)
|
48 |
43 |
connection.close()
|
49 |
44 |
else:
|
50 |
|
_Thread_bootstrap_inner(self)
|
|
45 |
_Thread__bootstrap_inner(self)
|
51 |
46 |
|
52 |
47 |
|
53 |
48 |
def install_tenant_aware_threads():
|
54 |
|
threading.Thread.__init__ = _new__init__
|
55 |
|
threading.Thread._bootstrap_inner = _new_bootstrap_inner
|
|
49 |
threading.Thread.start = _new_start
|
|
50 |
threading.Thread._bootstrap_inner = _new__bootstrap_inner
|