如何通过Python中的YAML配置文件检查与数据库的连接?

问题描述 投票:0回答:1

我有一个项目,需要一个YAML配置文件来检查与数据库的连接,并且我遇到一些问题:如果特定于主机的主机为none,它将自动为默认主机(本地主机)。我已经用示例文件对其进行了测试

以下但似乎我的代码有问题,当主机为空时,主机不会将默认值显示为loacalhost,否则它将不显示任何默认值。有人可以建议我吗?我在哪里错了?

我的样本文件data_source.yml:

database: 

dbopt:
   host: 
   port: 5432
   dbname: db1
   user: username
   password: 1234
   client_encoding: utf-8
   connect_timeout: 60
   sslmode: none

query:
   select * from manufacturing_product

query:
   select * from manufacturing_product

我的代码:

import yaml

class InvalidConfigError(Exception):
    pass

class DB:
    def __init__(self, dbconf):
        self._dbconf = dict(dbconf)

        # checking for database type
        dbtype = self.get_db_type()
        if dbtype != 'sqlite' and dbtype != 'postgres':
            raise InvalidConfigError(
                'E01001', 'Invalid database type, should be sqlite or postgres.')
        else:
            self.dbtype = dbtype

        #checking db option
        dbopt = self.__get_dbopt()
        if dbopt is None:
            raise InvalidConfigError(
                'E01002', 'Invalid database options.')
        else:
            self.dbopt = dbopt

        #checking host
        host = dbopt.get('host')
        if host is None or len(host) <= 0:
            self.host = 'localhost'
        else:
            self.host = host

        #checking dbname
        dbname = dbopt.get('dbname')
        if dbname is None or len(dbname) <= 0:
            raise Exception("Database name is required.")
        else:
            self.dbname = dbname

    def get_db_type(self):
        return self._dbconf['db']

    def __get_dbopt(self):
        return self._dbconf.get('dbopt')

    def get_db_host(self):
        return self.host

    def get_db_name(self):
        return self.dbname

with open('data_source.yml') as file:
    data = yaml.full_load(file)

    for item, doc in data.items():
        print(item, ":", doc)

    db = DB(data)

输出:

db : postgres
dbopt : {'host': None, 'port': 5432, 'dbname': 'meister_4ef1ef_mfgdata', 'user': 'analyzer', 'password': '9mtfkzvCqtaarlT2', 'client_encoding': 'utf-8', 'connect_timeout': 60, 'sslmode': 'none'}
query : select * from manufacturing_product
python pyyaml
1个回答
1
投票

您的代码很好,只是您没有正确检索它,我检查并得到了主机值为'localhost'

with open('data_source.yml') as file:
data = yaml.full_load(file)

for item, doc in data.items():
    print(item, ":", doc)

db = DB(data)

print("default host value:", db.get_db_host()) # added to test default host value 

输出:

db : postgres
dbopt : {'host': None, 'port': 5432, 'dbname': 'meister_4ef1ef_mfgdata', 'user': 
'analyzer', 'password': '9mtfkzvCqtaarlT2', 'client_encoding': 'utf-8', 
'connect_timeout': 60, 'sslmode': 'none'}
query : select * from manufacturing_product
default host value: localhost
© www.soinside.com 2019 - 2024. All rights reserved.