美文网首页
django连接多个数据库

django连接多个数据库

作者: Aedda | 来源:发表于2023-02-14 11:31 被阅读0次
    1. 构建DATABASES
    2. 配置DATABASE_MAPPING,原理是因为DatabaseAppsRouter需要用到DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
    import copy
    import datetime
    
    from django.conf import settings
    
    
    class DatabaseAppsRouter(object):
        """
        A router to control all database operations on models for different
        databases.
        In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
        will fallback to the `default` database.
        Settings example:
        DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
        """
    
        def db_for_read(self, model, **hints):
            """"Point all read operations to the specific database."""
            if model._meta.app_label in DATABASE_MAPPING:
                return DATABASE_MAPPING[model._meta.app_label]
            return None
    
        def db_for_write(self, model, **hints):
            """Point all write operations to the specific database."""
            if model._meta.app_label in DATABASE_MAPPING:
                return DATABASE_MAPPING[model._meta.app_label]
            return None
    
        def allow_relation(self, obj1, obj2, **hints):
            """Allow any relation between apps that use the same database."""
            db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
            db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
            if db_obj1 and db_obj2:
                if db_obj1 == db_obj2:
                    return True
                else:
                    return False
            return None
    
        def allow_syncdb(self, db, model):
            """Make sure that apps only appear in the related database."""
    
            if db in DATABASE_MAPPING.values():
                return DATABASE_MAPPING.get(model._meta.app_label) == db
            elif model._meta.app_label in DATABASE_MAPPING:
                return False
            return None
    
        def allow_migrate(self, db, app_label, model=None, **hints):
            """
            Make sure the auth app only appears in the 'auth_db'
            database.
            """
            if db in DATABASE_MAPPING.values():
                return DATABASE_MAPPING.get(app_label) == db
            elif app_label in DATABASE_MAPPING:
                return False
            return None
    
    
    DEFAULT_DATABASES = {
        # 'ENGINE': 'django.db.backends.mysql',
        'ENGINE': 'dj_db_conn_pool.backends.mysql',
        'NAME': 'xxxxxxx',
        'HOST': '127.0.0.1',
        'USER': 'xxxxx',
        'PASSWORD': 'xxxxxx',
        'PORT': 3306,
        'CONN_MAX_AGE': 0,    # 默认: 0  一个数据库连接的寿命,以秒为整数。使用 0 在每次请求结束时关闭数据库连接——这是 Django 的历史行为,使用 None 则是无限的持久连接。
        'OPTIONS': {
            'charset': 'utf8mb4',
            'connect_timeout': 30,  # 连接超时时间
        },
        'POOL_OPTIONS': {   # dj_db_conn_pool的参数
            'POOL_SIZE': 1,
            'MAX_OVERFLOW': 11,
            'RECYCLE': 60,
        }
    }
    
    
    TIDB_DATABASE_JYCM = copy.deepcopy(DEFAULT_DATABASES)
    TIDB_DATABASE_JYCM.update(dict(
        NAME='xxxx',
        HOST='xxxxx',
        USER='xxxxx',
        PASSWORD='xxxxxx',
        PORT=3307,
    ))
    
    # if settings.DEBUG:
    #     _DATABASE_DEFAULT.update({'HOST': '47.119.200.228', 'USER': 'suncent_test', 'PASSWORD': 'N&Gn397mMeE1t81D', })
    #     warning, warning_major = '0;33', '0;36'
    #     print(f"\033[{warning}m【{datetime.datetime.now()}】 WARNING 您目前所处的环境是\033[0m\033[{warning_major}mDEBUG\033[0m\033[{warning}m模式,所使用的数据库为测试库({_DATABASE_DEFAULT.get('HOST')})\033[0m")
    
    
    DATABASES = {
        'default': DEFAULT_DATABASES,
        'jycm': TIDB_DATABASE_JYCM,
    }
    DATABASE_MAPPING = {    # app-database映射
        'bgdata_jycm': 'jycm',
    }
    DATABASE_ROUTERS = ['bgdata_api.settings_database.DatabaseAppsRouter']
    
    # DJORM_POOL_PESSIMISTIC = True
    # DEBUG模式下打开这个可以查看sql语句
    # LOGGING = {
    #     'version': 1,
    #     'disable_existing_loggers': False,
    #     'handlers': {
    #         'console':{
    #             'level':'DEBUG',
    #             'class':'logging.StreamHandler',
    #         },
    #     },
    #     'loggers': {
    #         'django.db.backends': {
    #             'handlers': ['console'],
    #             'propagate': True,
    #             'level':'DEBUG',
    #         },
    #     }
    # }
    
    

    相关文章

      网友评论

          本文标题:django连接多个数据库

          本文链接:https://www.haomeiwen.com/subject/zcdekdtx.html