Django多DB如何写router

Django multiple DB how to write router

我有两个数据库,我写了一个 router.py 可以正确管理写入和读取,但是如果 read 数据库default 已关闭我也无法访问获取

的写入数据库
class TestRouter(object):

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

        if model._meta.app_label == 'read_app':
            return 'default'
        if model._meta.app_label == 'write_app':
            return 'write_db'        
        return None

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

        if model._meta.app_label == 'write_app':
            return 'write_db'
        return None

settings.py中:

DATABASE_ROUTERS = ['prj.dbrouter.TestRouter', ]

这是错误:

cnn = _connect(dsn, connection_factory=connection_factory, async=async)
OperationalError: could not connect to server: Connection refused Is the server running on host "192.168.2.1" and accepting TCP/IP connections on port 5432?

有没有办法告诉 django 忽略连接到 default db 的失败?

错误表明您要连接的数据库不接受请求或侦听来自主机“192.168.2.1”的请求。

postgresql.conf 文件中,更改 listen_addresses = '*'

让我详细说明你应该做什么,

  1. 在您的 settings.py 中添加数据库信息以及有关 routers.py 的信息:

settings.py

DATABASES = {
    'default': {},
    'master': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': 5432,
    },
    'slave': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': 5432,
    }
}
SLAVE_DATABASES = ['slave']

DATABASE_ROUTERS = ['path.to.your.routers.MasterSlaveRouter']
  1. 创建routers.py,它将处理设置中提到的数据库之间的读写请求切换:

routers.py

from django.conf import settings
import socket


def test_connection_to_db(database_name):
    try:
        db_definition = getattr(settings, 'DATABASES')[database_name]
        s = socket.create_connection(
            (db_definition['HOST'], db_definition['PORT']), 5)
        s.close()
        return True
    except:
        return False


class MasterSlaveRouter(object):
    def db_for_read(self, model, **hints):
        """
        Reads go to a randomly-chosen slave.
        """
        if test_connection_to_db('master'):
            return 'master'
        return 'slave'

    def db_for_write(self, model, **hints):
        """
        Writes always go to master.
        """
        if test_connection_to_db('master'):
            return 'master'
        return 'slave'

    def allow_relation(self, obj1, obj2, **hints):
        """
        Relations between objects are allowed if both objects are
        in the master/slave pool.
        """
        db_list = ('master', 'slave')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_migrate(self, db, model):
        """
        All non-auth models end up in this pool.
        """
        return True

所以现在,如果您的主服务器已关闭而从服务器已启动。请求将相应地转移,反之亦然。确保任一数据库已启动。

喂! :)