MySQL read-write separation technology in Django

Source: Internet
Author: User

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 certain rules to the different database (can be different types of database), we need to do is, Define different databases and define different routing rules.

First define our master-slave database:

DATABASES = {

' Default ': {

' ENGINE ': ' Django.db.backends.mysql ',

' NAME ': Sae.const.MYSQL_DB,

' USER ': Sae.const.MYSQL_USER,

' PASSWORD ': Sae.const.MYSQL_PASS,

' HOST ': Sae.const.MYSQL_HOST,

' PORT ': Sae.const.MYSQL_PORT,

},

' slave ': {

' ENGINE ': ' Django.db.backends.mysql ',

' NAME ': Sae.const.MYSQL_DB,

' USER ': Sae.const.MYSQL_USER,

' PASSWORD ': Sae.const.MYSQL_PASS,

' HOST ': Sae.const.MYSQL_HOST_S,

' PORT ': Sae.const.MYSQL_PORT,

},

}

Define our routing rules, there can be multiple routing rules, and each rule is a class. As shown below:

#-*-Coding:utf-8-*-

Class Dbrouter (object):

def db_for_read (self, model, **hints):

Return ' slave '

def db_for_write (self, model, **hints):

Return ' Default '

def allow_relation (self, obj1, Obj2, **hints):

Return None

def allow_syncdb (self, DB, model):

Return None

Finally, Add this routing rule to the setting.py:

Database_routers = [' Opensound.models.DBRouter ']

Because Django is not responsible for synchronization between master and slave databases, if you want to manipulate the data immediately after reading the data, you can explicitly use the primary database to read and modify the data.

>>> Author.objects.using (' other '). All ()
>>> my_object.save (using= ' legacy_users ')

Reference: https://docs.djangoproject.com/en/dev/topics/db/multi-db/

Http://www.truease.com/thread-262-1-1.html

MySQL read-write separation technology in Django

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.