python 解析外部json配置文件自动生成变量,并获取变量的变量名

标题

一、问题以及目标

程序开发过程中我们会有很多变量,为了产品化部署以及方便使用,我们通常需要将变量抽离成一个单独的配置文件,之后我们通过对配置文件进行修改,在不修改程序的情况下实现我们想要的目标。
我们很多时候需要在配置文件中添加参数,为了使得在配置文件中添加参数之后,解析配置文件的时候不需要修改,就能直接将新加的参数创建出对应的变量,开发一下工具达到这个目标。

二、

1、解析配置文件
配置示例

{
	"name": "charater", 
	"sex": "man"
}

2、通过字典自动创建变量

	# 传入字典, 以字典的键作为变量名, value作为变量值,通过递归自动创建所有变量
	@classmethod
    def createVariableByJson(cls, conf: dict):
        '''
        auto create variable through parse of config json file
        :param conf: dict, json parse of config file
        :return: None
        '''
        if type(conf) == dict:
            globals().update(conf)
            for k, v in conf.items():
                if type(v) == dict:
                    logger.debug(f"{k} : {v}")
                    cls.createVariableByJson(v)
                else:
                    logger.debug("value of type is {}, value is {}, no need to callback value".format(type(v), v))
        else:
            return None


# 导入需要的模块
import json
from loguru import logger
import inspect
import traceback

class Config:
    def __init__(self, file):
        '''
        pars configuration file and create variables through parsing results
        :param file: configuration file path
        '''
        self.file = file

    def readJsonConfig(self, mode: str = 'r', encoding: str = 'utf-8'):
        '''
        reading config file and convert string to dictionary
        :param mode: How to operate the configuration file
        :param encoding: Encoding format of configuration file
        :return: json or dict config
        '''
        with open(self.file, mode=mode, encoding=encoding) as f:
            s = f.read()
            try:
                conf = json.loads(s)
                return conf
            except json.decoder.JSONDecodeError as e:
                logger.debug("{} config json: \n{}".format(traceback.format_exc(), s))
                conf = eval(s)
                return conf
            finally:
                logger.debug('SUCCESS PARSING CONFIG FILE')
	# 通过解析出来的dict,递归创建所有变量
    @classmethod
    def createVariableByJson(cls, conf: dict):
        '''
        auto create variable through parse of config json file
        :param conf: dict, json parse of config file
        :return: None
        '''
        if type(conf) == dict:
            globals().update(conf)
            for k, v in conf.items():
                if type(v) == dict:
                    logger.debug(f"{k} : {v}")
                    cls.createVariableByJson(v)
                else:
                    logger.debug("value of type is {}, value is {}, no need to callback value".format(type(v), v))
        else:
            return None
	# 传入变量,获取变量名称以及变量的值
    @classmethod
    def get_variable_name(cls, variable):
        '''
        Pass in a variable as a parameter to get the name and value of the variable
        :param variable: Pass in a variable
        :return: [[var_name1, var_val1], [var_name1, var_val1]]
        >>> var = 'abc'
        >>> tup = get_variable_name(var)
        >>> tup
        [['var', 'abc']]
        '''
        logger.debug(locals())
        callers_local_vars = inspect.currentframe().f_back.f_locals.items()
        return [[var_name, var_val] for var_name, var_val in callers_local_vars if var_val is variable]

    def __call__(self, *args, **kwargs):
        '''
        read configuration and create variable
        :param args:
        :param kwargs:
        :return: None
        '''
        conf = self.readJsonConfig(*args, **kwargs)
        self.createVariableByJson(conf)

三、执行

file_name = "conf.json"
Config(file_name)()
print(Config.get_variable_name(promt_record_df_file_name))
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值