django mysql 读写分离
import socketfrom django.conf import settings
def test_connection_to_db(database_name):
try:
db_definition = getattr(settings, 'DATABASES')
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'
页:
[1]