django database separate read and write

django database separate read and write

1. Configuration Database

settings.py file
用SQLite:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'salve': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
    },
}

Or use mysql:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'user',
        'PASSWORD': 'passwd',
        'NAME': 'db_read'
    },
    'slave': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',
        'PORT': 8306,
        'USER': 'root',
        'PASSWORD': 'mysqlpwd',
        'NAME': 'db_write'
    }
}

 

2. Create models and perform database migration (slightly)
3. separate read and write operations

- Manually separate read and write

------views.py view files ------ 
object.using ( 'default') This specifies which library use, 
from django.shortcuts Import HttpResponse
 from . Import Models 

DEF the Write (Request): 
    Models. Products.objects.using ( ' default ' ) .create (name = ' hairy ' , Age = 12 is )
     return the HttpResponse ( ' write success ' ) 

DEF Read (Request): 
    obj = models.Products.objects.filter (ID = . 1) .using ( ' Salve ' ) .first ()
     return the HttpResponse (obj.name)

 

- Automatic separate read and write

To automatically configure routing database.
New router.py file
class Router:
     DEF db_for_read (Self, Model, ** hints):
     '' ' 
    db_for_read fixed wording, the read operation of the automatic matching 
    ' '' 
        return  ' Slave ' 
    DEF db_for_write (Self, Model, ** hints):
     '' ' 
    db_for_write fixed writing, the write operation of the automatic matching 
    '' ' 
        return  ' default '

 

Configuring router

------ settings.py ------ file 
DATABASE_ROUTERS = [ ' router.Router ' ,]  

 

4. a master multi-slave scheme

New router.py file
class Router:
     DEF db_for_read (Self, Model, ** hints):
         "" " 
        randomly selecting a database to read 
        " "" 
        Import Random
         return The random.choice ([ ' salve1 ' , ' slave2 ' , ' slave3 ' ])
     DEF db_for_write (Self, Model, ** hints):
         "" " 
        select the primary database when writing 
        " "" 
        return  ' default '

Configuring router

------ settings.py ------ file 
DATABASE_ROUTERS = [ ' router.Router ' ,]  

The sub-library sub-table

New router.py file
database separation between the app, such as go app01 database salve1, app02 go database slave2
class Router:
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'app01':
            return 'salve1'
        if model._meta.app_label == 'app02':
            return 'slave2'
    def db_for_write(self, model, **hints):
       if model._meta.app_label == 'app01':
            return 'slave1'
       if model._meta.app_label == 'app02':
            return 'slave2'

Configuring router

------ settings.py ------ file 
DATABASE_ROUTERS = [ ' router.Router ' ,]  

 Note the following:

manage.py makemigraions Python 

Python manage.py the migrate App Name --databse = alias name of the profile data 

manually: 
    models.UserType.objects.using ( ' DB1 ' ) .create (title = ' normal user ' ) 
    Result = Models . .UserType.objects.all () the using ( ' default ' ) 
    
automatic operation: 
    class Router1:
         DEF db_for_read (Self, Model, ** hints):
             "" " 
            Attempts Designates, in Models to Go to auth_db Read the auth. 
            " "" 
            return  ' DB1 ' 

        DEF db_for_write (Self,model, **hints):
            """
            Attempts to write auth models go to auth_db.
            """
            return 'default'

    配置:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            },
            'db1': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join(BASE_DIR, 'db1.sqlite3'),
            },
        }
        DATABASE_ROUTERS = ['db_router.Router1',]
        
    使用:
        models.UserType.objects.create(title='VVIP')

        result = models.UserType.objects.all()
        print(result)
                            
    补充:粒度更细
        class Router1:
            def db_for_read(self, model, **hints):
                """
                Attempts to read auth models go to auth_db.
                """
                if model._meta.model_name == 'usertype':
                    return 'db1'
                else:
                    return 'default'

            def db_for_write(self, model, **hints):
                """
                Attempts to write auth models go to auth_db.
                """
                return 'default'Step One:#
    app02 tables created in the database db1
    app01 tables created in the default database
Question:
    
    
        manage.py makemigraions Python 
    
    # Step two: 
        app01 tables created in the default database 
        Python manage.py the migrate app01 --database = default 
    
    # The third step: 
        in app02 db1 database table is created in 
        Python manage.py the migrate app02 - = Database DB1 
        
    # manually: 
        m1.UserType.objects.using ( ' default ' ) .create (title = ' VVIP ' ) 
        m2.Users.objects.using ( ' DB1 ' ) .create (name = ' VVIP ' , In Email = ' XXX ' )
     # 自动操作:
        配置: 
            class Router1:
                def db_for_read(self, model, **hints):
                    """
                    Attempts to read auth models go to auth_db.
                    """
                    if model._meta.app_label == 'app01':
                        return 'default'
                    else:
                        return 'db1'

                def db_for_write(self, model, **hints):
                    """
                    Attempts to write auth models go to auth_db.
                    """
                    if model._meta.app_label == 'app01':
                        return 'default'
                    else:
                        return 'db1'

            DATABASE_ROUTERS = ['db_router.Router1',]
        
        使用: 
            m1.UserType.objects.using('default').create(title='VVIP')
            m2.Users.objects.using('db1').create(name='VVIP',email=' XXX ' ) 
Other: 
    restrains database migration: 
        class Router1:
             DEF allow_migrate (Self, DB, app_label, MODEL_NAME = None, ** hints):
                 "" " 
                All the auth non-End Models in the this up the pool. 
                " "" 
                IF DB == ' DB1 '  and app_label == ' app02 ' :
                     return True
                 elif DB == ' default '  and app_label == ' app01 ' :
                    return True
                 the else :
                     return False 
                
                # If it returns None, the follow-up to represent the router, if there is no follow-up router, the equivalent of returns True 
                
            DEF db_for_read (Self, Model, ** hints):
                 "" " 
                Attempts Designates, in the Read auth Models to Go auth_db to. 
                "" " 
                IF model._meta.app_label == ' app01 ' :
                     return  ' default ' 
                the else :
                     return  ' DB1 ' 

            DEF db_for_write (Self, Model, ** hints):
                 """
                Attempts to write auth models go to auth_db.
                """
                if model._meta.app_label == 'app01':
                    return 'default'
                else:
                    return 'db1'



docker run -it -p 8000:8000 --name=mydemo -v /home/test/:/usr/lqz my_django_test python /usr/lqz/djangotest2/manage.py runserver 0.0.0.0:8000


docker run -it -p 8000:8000 --name=mydemo_lqz_django -v /home/test/:/usr/lqz lqz_django_v1 python /usr/lqz/djangotest2/manage.py runserver 0.0.0.0:8000

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/Gaimo/p/12177485.html