django database router是个好东西

今天给sentry加了MySQL读写分离机制,记录一下:

DATABASES里,(sentry的脾气比较怪)保留名为default的配置,写master数据库的参数;新增一个名为slave的配置,使用只读用户名密码,或开启服务器端read only
然后增加一个类,带四个函数:

class DatabaseRWSplitRouter(object):
    def db_for_read(self, model, **hints):
        return 'slave'

    def db_for_write(self, model, **hints):
        return 'default'

    def allow_relation(self, model1, model2, **hints):
        return True

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if db == 'slave':
            return None
        else:
            return True

再把这个注册进去

DATABASE_ROUTERS = (DatabaseRWSplitRouter(), )

注意这个注册,可以写字符串形式的dotted_path也可以是一个对象,我偷懒就直接写了一个对象。

This entry was posted in 默认分类 and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *