Django multiple databases, Django connects to all of them first?

Example database configuration for MySQL:

DATABASES = {
    'auth_db': {
        'NAME': 'auth_db',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'swordfish',
    },
    'master': {
        'NAME': 'master',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'spam',
    },
    'slave1': {
        'NAME': 'slave1',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'eggs',
    },
    'slave2': {
        'NAME': 'slave2',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'bacon',
    },
}

      

Does Django connect to all of them first, even if some of the databases aren't being used at all? eg.

Using native cursors with multiple databases

If you are using more than one database, you can use django.db.connections to get the connection (and cursor) for a specific database. django.db.connections is a dictionary-like object that allows you to get a specific connection using its alias:

from import connections django.db

cursor = connections ['my_db_alias']. cursor ()

So 1. does the connection object contain connections already made? Or does it connect when a cursor request is made? 2. Is there a way to change this default behavior and establish connections on demand (all queries are raw queries and all databases are MySQL)?

+3


source to share


2 answers


A persistent connection will be made to the requested database the first time it is accessed with django.db.connections

. That is, connections are lazily evaluated and only connect on first use. The relevant code is in django/db/__init__.py

the class ConnectionHandler

.



Links will not be automatically removed upon request, but the link will remain until disconnected. If DATABASES

there are no records in that are never used, there will be no connection to these databases.

+4


source


Django uses a default alias database when no other database is selected. If you don't have a default database, you must be careful to always specify the database you want to use. In your case, you don't need the default or auth_db for the auth user, etc.

Anyway the connections should be on demand, you can connect to MYSQL Explorer and issue the following command to see the active connections and then query the cursor and check the command result and compare again. The command is as follows:

SHOW PROCESSLIST

      



http://dev.mysql.com/doc/refman/5.1/en/show-processlist.html

Please report your results.

-1


source







All Articles