如何检查Toml转换后的字典指定键存在且对应值非空?
问题描述
我有如下Toml文件:
[default] conf_path = "d" prefix = "p" suffix = "s"
转换为字典后结构如下:
{'default': {'conf_path': 'd', 'prefix': 'p', 'suffix': 's'}}
需要完成两项校验:
- 字典中
default键必须存在 default对应的嵌套字典里,conf_path、prefix、suffix三个键需全部存在,且对应的值不能是空字符串''或None
现有代码如下,但在验证嵌套字典的键和值时遇到困难:
import os from pathlib import Path import tomlkit import const def get_config_path() -> str: """ 获取配置文件路径 """ default_path = os.path.expanduser(const.CONFIG_PATH) final_path = os.environ.get('CONFIG_PATH', default_path) return final_path def check_toml(): conf = Path(get_config_path()) default_table = ['default', 'conf_path', 'prefix', 'suffix'] if conf.exists(): toml_dict = tomlkit.loads(Path(get_config_path()).read_text()) d = toml_dict['default'] for key, value in d.items(): d = key else: d = 'File does not exist.' return d
我能单独校验单个键,比如:
if toml_dict['default'].get('conf_path') not in (None, ''):
但不知道如何同时校验三个键均存在且值非空,并返回清晰的校验结果,考虑过用列表实现,但不知道具体操作。
解决方案
可以通过分步校验+收集错误信息的方式实现,逻辑清晰还能返回明确的结果。修改后的check_toml函数如下:
import os from pathlib import Path import tomlkit import const def get_config_path() -> str: """ 获取配置文件路径 """ default_path = os.path.expanduser(const.CONFIG_PATH) final_path = os.environ.get('CONFIG_PATH', default_path) return final_path def check_toml(): conf = Path(get_config_path()) required_inner_keys = ['conf_path', 'prefix', 'suffix'] # 检查配置文件是否存在 if not conf.exists(): return "错误:配置文件不存在" # 读取并解析Toml文件,捕获解析异常 try: toml_dict = tomlkit.loads(conf.read_text()) except Exception as e: return f"错误:配置文件解析失败 - {str(e)}" # 检查外层'default'键是否存在 if 'default' not in toml_dict: return "错误:配置文件中缺少'default'表" default_section = toml_dict['default'] # 批量检查内层键和值的有效性 errors = [] for key in required_inner_keys: # 先检查键是否存在 if key not in default_section: errors.append(f"缺少必填键:{key}") continue # 再检查值是否为空或None value = default_section[key] # 若需要过滤全空格的情况就保留strip(),否则直接判断value in (None, '') if value is None or (isinstance(value, str) and value.strip() == ''): errors.append(f"键[{key}]的值为空或无效") # 返回最终校验结果 if not errors: return "配置文件校验通过" else: return "配置文件校验失败:\n" + "\n".join(errors)
核心逻辑说明:
- 分层校验:从文件存在性→解析有效性→外层键存在性→内层键值有效性,逐步排查问题,避免一步出错就终止校验
- 错误收集:用列表
errors汇总所有问题,一次性返回所有校验失败点,不用反复调试 - 值有效性判断:增加了对字符串类型的判断,避免非字符串类型调用
strip()报错;如果不需要过滤全空格,直接改成value in (None, '')即可 - 异常处理:捕获Toml解析异常,避免文件格式错误导致程序崩溃
内容的提问来源于stack exchange,提问作者uncrayon
相关产品推荐
相关产品推荐

