读取 Python 中的 YAML 配置文件

Read YAML configuration file in Python

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

我的 test.yaml 文件:

database: 

dbopt:
   host: bvcbvcbvcb.com
   port: 5432
   dbname: db1
   user: username
   password: 1234
   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

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

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

您的代码中缺少几段代码,您的函数 __init__ 从未被调用过。您可能从某个带有 class 的示例中复制了它,它也有一个方法 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': 'bvcbvcbvcb.com', 'port': 5432, 'dbname': 'db1', 'user': 'username', 'password': '1234', 'client_encoding': 'utf-8', 'connect_timeout': 60, 'sslmode': 'none'}
query : select * from manufacturing_product

然后给出:

init raise InvalidConfigError( main.InvalidConfigError: ('E01001', 'Invalid database type, should be sqlite or postgres.') process error Command '['ryd', '--force', 'so-60160957.ryd']' returned non-zero exit status 1.

评论

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

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