能够检查db connection host或name(不是db name而是设置)?django公司

p4rjhz4m  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(415)

我不是要检查连接的db名称,我在django中设置了多个数据库,还使用了 database route 创建 failover 但是我想知道我是否可以得到连接主机的名称或者设置的名称。。。
例如

DATABASES = {
    'default': {  # trying to get this name 'default'
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_name',
        'USER': 'euser',
        'PASSWORD': 'password',
        'HOST': 'host', # trying to get this host name 'host'
        'PORT': 3306,
    },
    'node2': {  # trying to get this name 'node2'
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_name',
        'USER': 'euser',
        'PASSWORD': 'password',
        'HOST': 'host2',  # trying to get this host name 'host2'
        'PORT': 3306,
    },
}

有没有可能得到那些我在上面注解掉的名字?对于我的故障转移,我试图发送一封电子邮件,如果另一个数据库正在使用,但它将是伟大的,如果我能得到特别是 host 所以对我来说比较容易
p、 有没有可能改变名字 default 其他名字?我试着改变它,结果会出错。似乎我必须至少有一个数据库设置名 default 提前谢谢你的帮助。

ecfsfe2w

ecfsfe2w1#

所以,做:

import pprint  # Makes it sooo pretty :)
from django.db import connection
print(pprint.pformat(connection.settings_dict))

将为您提供当前连接设置。例如,上面的代码应该打印如下内容:

{'ATOMIC_REQUESTS': False,
 'AUTOCOMMIT': True,
 'CONN_MAX_AGE': 600,
 'ENGINE': 'django.db.backends.postgresql',
 'HOST': 'localhost',
 'NAME': 'stack_overflow',
 'OPTIONS': {},
 'PASSWORD': '***',
 'PORT': '5432',
 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None},
 'TEST_NAME': 'stack_overflow_test',
 'TIME_ZONE': None,
 'USER': 'postgres'}

所以您应该可以通过 connection.settings_dict['HOST']

相关问题