3

我正在将 Django 1.8 项目从单个数据库设置移动到写入器/读取器设置。我遇到了Django bug 23718中描述的问题,但描述的解决方法似乎没有帮助。

有没有人遇到过类似的问题?相关代码段如下:

路由器:

class DatabaseRouter(object):

    """Router to handle separation of reads and writes."""

    def db_for_read(self, model, **hints):
        """Reads go to a read replica."""
        return 'read'

    def db_for_write(self, model, **hints):
        """Writes always go to default."""
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        """Allow relations bet/n objects in the same DB cluster."""
        db_list = ('default', 'read')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """All models end up in this pool."""
        return True

相关数据库设置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DB_NAME,
        'USER': DB_USER,
        'PASSWORD': DB_PASS,
        'HOST': DB_WRITE
    },
    'read': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DB_NAME,
        'USER': DB_USER,
        'PASSWORD': DB_PASS,
        'HOST': DB_READ,
        'TEST': {
            'MIRROR': 'default',
        },
    }
}

DATABASE_ROUTERS = ['my_project.routers.DatabaseRouter']

解决复制测试用例:

class ReplicationTestCase(TestCase):

    @classmethod
    def setUpClass(cls):
        super(ReplicationTestCase, cls).setUpClass()
        connections['read']._orig_cursor = connections['read'].cursor
        connections['read'].cursor = connections['default'].cursor

    @classmethod
    def tearDownClass(cls):
        connections['read'].cursor = connections['read']._orig_cursor
        super(ReplicationTestCase, cls).tearDownClass()

有什么弹出来的吗?如果这也有用的话,我很乐意从我们的测试环境中提供堆栈跟踪。谢谢!

4

0 回答 0