[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

[python] 關於 numpy 以及1~5維度的資料

[python] 關於 numpy 以及1~5維度的資料

[Week 2] JavaScript - 變數、陣列、物件、== 與 ===

[Week 2] JavaScript - 變數、陣列、物件、== 與 ===

r3:0 異世界網站挑戰 - 破關紀錄

r3:0 異世界網站挑戰 - 破關紀錄


Comments