标题
一、问题以及目标
程序开发过程中我们会有很多变量,为了产品化部署以及方便使用,我们通常需要将变量抽离成一个单独的配置文件,之后我们通过对配置文件进行修改,在不修改程序的情况下实现我们想要的目标。 我们很多时候需要在配置文件中添加参数,为了使得在配置文件中添加参数之后,解析配置文件的时候不需要修改,就能直接将新加的参数创建出对应的变量,开发一下工具达到这个目标。
二、
1、解析配置文件 配置示例
{
"name": "charater",
"sex": "man"
}
2、通过字典自动创建变量
@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')
@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))
|