读取Python中的YAMLl配置文件

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

我正在尝试读取YAML配置文件并将其显示给终端。现在,我想尝试诸如检查YAML文件中的数据库(db)不是Sqlite还是Postgres的操作,然后会引发异常,但我不知道如何。我尝试了但失败了,我在做什么错?

我的test.yaml文件:

db: mysql
dbopt:
   host: zppp8alnTQc6jpfb.cds6ifjzc2el.ap-northeast-1.rds.amazonaws.com
   port: 5432
   dbname: meister_4ef1ef_mfgdata
   user: analyzer
   password: 9mtfkzvCqtaarlT2
   client_encoding: utf-8
   connect_timeout: 60
   sslmode: none
query: select * from manufacturing_product

我的代码:

# process_yaml.py file`
import yaml

with open(r'D:\Python\test.yaml') as file:
    # The FullLoader parameter handles the conversion from YAML
    # scalar values to Python the dictionary format
    data = yaml.full_load(file)

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

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

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

我的程序仍然无法捕获异常。我的终端机:

db : mysql
dbopt : {'host': 'zppp8alnTQc6jpfb.cds6ifjzc2el.ap-northeast-1.rds.amazonaws.com', '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个回答
0
投票

您的代码中缺少几段,并且永远不会调用函数__init__。您可能从带有类的示例中复制了该示例,该类也具有方法get_db_type()

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

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


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

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


    db = DB(data)

哪些印刷品:

db : mysql
dbopt : {'host': 'zppp8alnTQc6jpfb.cds6ifjzc2el.ap-northeast-1.rds.amazonaws.com', 'port': 5432, 'dbname': 'meister_4ef1ef_mfgdata', 'user': 'analyzer', 'password': '9mtfkzvCqtaarlT2', 'client_encoding': 'utf-8', 'connect_timeout': 60, 'sslmode': 'none'}
query : select * from manufacturing_product

然后给出:

init引发InvalidConfigError(main。InvalidConfigError :(“ E01001”,“无效的数据库类型,应为sqlite或postgres。”)进程错误命令'['ryd','--force','so-60160957.ryd']'返回非零退出状态1。

评论

# The FullLoader parameter handles the conversion from YAML
# scalar values to Python the dictionary format

而不是商标。 FullLoader解析YAML并尝试将所有节点实例化为Python对象:YAML映射为dict,YAML序列为列表,以及标量为Python类型(字符串,整数,浮点,布尔等)的YAML节点。

© www.soinside.com 2019 - 2024. All rights reserved.