config_helper.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import os
  2. import yaml
  3. class ConfigHelper:
  4. _instance = None
  5. # 默认配置文件路径
  6. default_config_path = os.path.join(os.path.dirname(__file__), '..',
  7. 'config.yml')
  8. # 类变量存储加载的配置
  9. _config = None
  10. _path = None
  11. def __new__(cls, *args, **kwargs):
  12. if not cls._instance:
  13. cls._instance = super(ConfigHelper, cls).__new__(cls)
  14. return cls._instance
  15. def load_config(self, path=None):
  16. if self._config is None:
  17. if not path:
  18. # print(f"使用默认配置文件:{self.default_config_path}")
  19. self._path = self.default_config_path
  20. else:
  21. self._path = path
  22. if not os.path.exists(self._path):
  23. raise FileNotFoundError(f"没有找到文件或目录:'{self._path}'")
  24. with open(self._path, 'r', encoding='utf-8') as file:
  25. self._config = yaml.safe_load(file)
  26. # 合并环境变量配置
  27. self._merge_env_vars()
  28. # print(f"加载的配置文件内容:{self._config}")
  29. return self._config
  30. def _merge_env_vars(self, env_prefix="APP_"): # 环境变量前缀为 APP_
  31. for key, value in os.environ.items():
  32. if key.startswith(env_prefix):
  33. config_key = key[len(env_prefix):].lower()
  34. self._set_nested_key(self._config, config_key.split('__'),
  35. value)
  36. def _set_nested_key(self, config, keys, value):
  37. if len(keys) > 1:
  38. if keys[0] not in config or not isinstance(config[keys[0]], dict):
  39. config[keys[0]] = {}
  40. self._set_nested_key(config[keys[0]], keys[1:], value)
  41. else:
  42. config[keys[0]] = value
  43. def get(self, key:str, default:str=None):
  44. if self._config is None:
  45. self.load_config(self._path)
  46. keys = key.split('.')
  47. config = self._config
  48. for k in keys:
  49. if isinstance(config, dict) and k in config:
  50. config = config[k]
  51. else:
  52. return default
  53. return config
  54. def get_bool(self, key:str)->bool:
  55. val = str(self.get(key,"0"))
  56. return True if val.lower() == "true" or val == "1" else False
  57. def get_int(self, key:str, default:int=0)->int:
  58. val = self.get(key)
  59. if not val:
  60. return default
  61. try :
  62. return int(val)
  63. except ValueError:
  64. return default
  65. def get_all(self):
  66. if self._config is None:
  67. self.load_config(self._path)
  68. return self._config