1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33import socket
from django.conf import settings
def test_connection_to_db(database_name):
try:
db_definition = getattr(settings, 'DATABASES')[database_name]
s = socket.create_connection((db_definition['HOST'], 3306), 2)
s.close()
return True
except (AttributeError, socket.timeout) as e:
return False
class FailoverRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'ospf' and test_connection_to_db('slave'):
return 'slave'
return 'default'
def db_for_write(self, model, **hints):
"Point all writes to the default db"
return 'default'
def allow_relation(self, obj1, obj2, **hints):
db_list = ('default', 'slave')
if obj1.state.db in db_list and obj2.state.db in db_list:
return True
return None
def allow_syncdb(self, db, model):
"Make sure only the default db allows syncdb"
return db == 'default'