使用多个数据库进行Django 1.8测试时出错

时间:2017-04-27 23:29:44

标签: python django database-mirroring multi-database

我将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()

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

0 个答案:

没有答案