Recently, we need to use Django's MySQL read-write separation technology, looked up some information, the method was sorted down.
In the Django implementation of the MySQL read and write separation, in fact, the different read and write requests according to a certain rules to the different database (can be different types of database), we need to do is to define different databases, define different routing rules. Of course, if you need to manually implement MySQL master-slave synchronization.
databases = { ' Default ': { ' ENGINE ': ' Django.db.backends.mysql ', ' NAME ': ' OSPF ', ' USER ': ' root ', ' PASSWORD ': ' Hunantv ', }, ' slave ': { ' ENGINE ': ' Django.db.backends.mysql ', ' NAME ': ' OSPF ', ' USER ': ' OSPF ', ' PASSWORD ': ' hunantv ', ' HOST ': ' 192.168.8.52 ' }}
IMPORT SOCKETFROM DJANGO.CONF IMPORT SETTINGSDEF 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 Falseclass 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 '
Db_for_read. There is a read so the name Incredibles is where to read. App_label is the name of the app:
Because I want users, permissions tables, or read from the main database, this limit is added. TEST_CONNECTION_TO_DB is to judge whether the database is abnormal and, in the case of an exception, is automatically read to the primary database.
Finally, add this routing rule to the setting.py:
Database_routers = [' Lvs.models.FailoverRouter']
>>> Author.objects.using (' Default '). All ()
>>> my_object.save (using= ' default ')
This article is from the "Webgame Automation Operations" blog, please be sure to keep this source http://mstools.blog.51cto.com/1104047/1680195
Django MySQL read-write separation