在DTCloud中支持yaml文件

扶程星云 2023-02-07 17:34:44
在项目实施中需要一个统一的撰写配置文件规范而且配置文件较为通用且易读,有没有解决方案呢?答案是有的,目前介绍一种配置文件规范 「YAML 语言」.本工具专用于对项目config下的config.yaml文件操作,填补DTCloud原读取.conf文件若干不足之处,期望大部分项目配置文件通过这个工具读取。 原则本工具只供读取配置文件使用.

使用方法:YamlConfig.read("list.inCloud", "defInfo222") ,传入要读取的地址,多级地址用.分隔。

公用代码

# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# DTCloud360
# QQ:35350428
# 邮件:35350428@qq.com
# 手机:13584935775
# 作者:Nebula Fortune(扶程星云)
# 公司网址: http://www.dtcloud360.com/
# Copyright 中亿丰数字科技集团有限公司
# 日期:2023/2/7 10:16
# 文件:     config_public.py
# 备注:
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

def get_config_by_path(pathStr, configStr):
    """读取传入的配置文件,读取匹配路径的值

    传入要读取的配置文件和字典路径,在配置文件中找到该路径的值,返回该值,如果没有该值或读取出错,则返回None,多重路径通过.分隔

    args:
       pathStr:要解析的路径,多重路径用.分隔,比如 list.inCloud
       configStr:读到的config文件内容

    return:
        value_str: 读取到的值
    """
    value_str = configStr
    path_list = pathStr.split('.')
    for key in path_list:
        if key in value_str:
            value_str = value_str[key]
        else:
            return None
    return value_str

主要代码

# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# DTCloud360
# QQ:35350428
# 邮件:35350428@qq.com
# 手机:13584935775
# 作者:Nebula Fortune(扶程星云)
# 公司网址: http://www.dtcloud360.com/
# Copyright 中亿丰数字科技集团有限公司
# 日期:2023/2/7 10:16
# 文件:     yaml_config.py
# 备注:
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

import logging
import os.path
import warnings
import yaml

from config_public import get_config_by_path

# 换源  pip config set global.index-url https://pypi.douban.com/simple/
# 换回默认源
# pip config unset global.index-url
# pip install pyyaml -i https://pypi.douban.com/simple


_logger = logging.getLogger(__name__)


class YamlConfig:
    """yaml配置文件读取工具

     在项目实施中需要一个统一的撰写配置文件规范而且配置文件较为通用且易读,有没有解决方案呢?答案是有的,目前介绍一种配置文件规范 「YAML 语言」.
      本工具专用于对项目config下的config.yaml文件操作,填补DTCloud原读取.conf文件若干不足之处,期望大部分项目配置文件通过这个工具读取。
      原则本工具只供读取配置文件使用.
    """
    projectPath = os.path.abspath(os.path.join(os.getcwd(), "../.."))  # 当前项目目录
    configFullPath = os.path.join(projectPath, "config")  # 当前配置项目配置文件目录
    configFileFullPath = os.path.join(configFullPath, "config.yaml")  # 当前配置文件全路径

    @classmethod
    def read(cls, pathStr, defStr):
        """读取配置文件里面的值

        传入要读取的路径和默认值,在配置文件中找到该路径的值,返回该值,如果没有该值或读取出错,则返回默认值,多重路径通过.分隔

        args:
           pathStr:要解析的路径,多重路径用.分隔,比如 list.inCloud
           defStr:默认返回值,如果不成功,则返回默认值

        returns:
            value: 读取到的值
            err: 出错信息。如果err为None,则是真正读到了值,否则返回的值就是默认的值。

        Raises:
            yaml.YAMLError: yaml读取异常
            路径不存在
            文件不存在
            未读到值
        """
        err = None
        if not os.path.exists(YamlConfig.configFullPath):  # 判断路径是否存在
            err = f'路径{YamlConfig.configFullPath}不存在.'
            return defStr, err

        if not os.path.isfile(YamlConfig.configFileFullPath):  # 判断文件是否存在
            err = f'文件{YamlConfig.configFileFullPath}不存在'
            return defStr, err
        with open(YamlConfig.configFileFullPath, "r", encoding='utf-8') as stream:
            try:
                config = yaml.safe_load(stream)
                value = get_config_by_path(pathStr, config)
                if value is None:
                    value = defStr
                    err = "未读到值"
                return value, err
            except yaml.YAMLError as e:
                err = f'YamlConfig read err:{e}'
                return defStr, err

    @classmethod
    def new(cls, data):
        """谨慎使用:会清空原文件所有数据,不做任何检查,直接插入纪录!"""
        warnings.warn("谨慎使用:会清空原文件所有数据,不做任何检查,直接插入纪录!", DeprecationWarning)
        err = None
        if not os.path.exists(YamlConfig.configFullPath):  # 判断路径是否存在
            try:
                os.makedirs(YamlConfig.configFullPath)
            except Exception as e:
                err = f'路径{YamlConfig.configFullPath}创建失败, err:{e}'
                return err

        with open(YamlConfig.configFileFullPath, 'w', encoding='utf-8') as f:
            yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
        return err


if __name__ == '__main__':
    date = {
        "name": "Tom",
        "age": 23,
        "sex": "man",
        'list': {'inCloud': [1, 2, 3]}
    }
    YamlConfig.new(date)
    print(YamlConfig.read("list.inCloud", "defInfo222"))
# print(configFullPath)

 

...全文
37 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

4,666

社区成员

发帖
与我相关
我的任务
社区描述
DTCloud是一套基于Pthon+Go开源商业应用程序.主要面向建筑工程行业,物联网行业,数字化行业,打造的企业信息一体化的解决方案。
物联网 企业社区
社区管理员
  • 中亿丰数字科技集团有限公司
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧