Skip to content

Commit 6bfb050

Browse files
committed
chore(passport): optimize the use of master and slave database rules
1 parent 31540a8 commit 6bfb050

1 file changed

Lines changed: 18 additions & 1 deletion

File tree

rootfs/api/routers.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,31 @@
1+
from asgiref.local import Local
12
from django.conf import settings
23

34

45
class DefaultReplicaRouter(object):
6+
"""
7+
If a model of the current thread or coroutine has used the master db,
8+
the model will also use the master in the future.
9+
This can avoid the problem that the slave database is not synchronized
10+
because a transaction is not committed.
11+
"""
12+
thread_critical = False
13+
14+
def __init__(self):
15+
self._tracker = Local(self.thread_critical)
516

617
def db_for_read(self, model, **hints):
7-
if 'replica' in settings.DATABASES:
18+
tracker_key = ".".join([model.__module__, model.__name__])
19+
if hasattr(self._tracker, tracker_key):
20+
return getattr(self._tracker, tracker_key)
21+
elif 'replica' in settings.DATABASES:
822
return 'replica'
923
return 'default'
1024

1125
def db_for_write(self, model, **hints):
26+
tracker_key = ".".join([model.__module__, model.__name__])
27+
if 'replica' in settings.DATABASES:
28+
setattr(self._tracker, tracker_key, 'default')
1229
return 'default'
1330

1431
def allow_relation(self, obj1, obj2, **hints):

0 commit comments

Comments
 (0)