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

平阳

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

下面,但似乎我的代码有问题,主机在为空时不会将默认值显示为 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)

输出:

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
阿德南

您的代码很好,只是您没有正确检索它,我检查并获得了主机值为“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': 1234, 'dbname': 'xyz', 'user': 'abc', 'password': 'pass', 'client_encoding': 'utf-8', 'connect_timeout': 100, 'sslmode': 'none'}
insopt : {'table': 'tries', 'out': 'qubna', 'bl': 'tghqua'}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章