[Python] How to setup a json or yaml to an object in python


Posted by jerryeml on 2021-03-04

[PY] 如何把設定檔變成一個物件

Nowadays, we offen use yaml, json or ini as a config file to control infra of an application

Before:

def load_global_params_config(py_root_path=dirname(__file__)) -> dict:
    config_path = os.path.join(py_root_path, "circles_params.yaml")
    with open(config_path) as f:
        global_params = yaml.load(f.read(), Loader=yaml.SafeLoader)

    logging.debug(f"loading global params config: {config_path}")
    return global_params

class MonitorUtil(object):
    def __init__(self, circle_name):
        self.circle_name = circle_name
        self.subscription_id = load_global_params_config()['common_var']['subscription_id']
        self.user_name = load_global_params_config()['circle_var'][circle_name]['user_name']  
        self.az_pat = os.getenv('AZ_PAT')

After

def load_app_config_to_obejct(py_root_path=dirname(__file__)) -> object:
    config_path = os.path.join(py_root_path, "circles_params.yaml")
    with open(config_path) as f:
        global_params = yaml.load(f.read(), Loader=yaml.SafeLoader)

    logging.debug(f"loading global params config: {config_path}")

    class config_obj(object):
        def __init__(self, dict_tpye):
            self.__dict__.update(dict_tpye)

    return json.loads(json.dumps(global_params), object_hook=config_obj)

class MonitorUtil(object):
    def __init__(self, circle_name):
        self.circle_name = circle_name
        self.subscription_id = load_global_params_config().common_var.subscription_id
        self.user_name = load_global_params_config().circle_var.circle_name.user_name  
        self.az_pat = os.getenv('AZ_PAT')

reference
https://stackoverflow.com/questions/1305532/convert-nested-python-dict-to-object


#JSON #Python #object #OOP







Related Posts

jQuery初學筆記-2

jQuery初學筆記-2

LidemyOJ 解題 - 聯誼門票搶起來

LidemyOJ 解題 - 聯誼門票搶起來

service worker

service worker


Comments