You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1 月之前
4 天之前
1 月之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import json
  2. import logging
  3. import os
  4. import pickle
  5. import copy
  6. from common.log import logger
  7. # from common.log import logger
  8. # 示例配置文件
  9. DEBUG = True
  10. available_setting = {
  11. "qwen_access_key_id": "",
  12. "qwen_access_key_secret": "",
  13. "debug": False,
  14. #redis 配置
  15. "redis_host":"",
  16. "redis_port":0,
  17. "redis_password":"",
  18. "redis_db":0,
  19. # kafka配置
  20. "kafka_bootstrap_servers":"",
  21. # aiops平台
  22. "aiops_api":"",
  23. "wx_chat_api":""
  24. }
  25. class Config(dict):
  26. def __init__(self, d=None):
  27. super().__init__()
  28. if d is None:
  29. d = {}
  30. for k, v in d.items():
  31. self[k] = v
  32. # user_datas: 用户数据,key为用户名,value为用户数据,也是dict
  33. self.user_datas = {}
  34. def __getitem__(self, key):
  35. if key not in available_setting:
  36. raise Exception("key {} not in available_setting".format(key))
  37. return super().__getitem__(key)
  38. def __setitem__(self, key, value):
  39. if key not in available_setting:
  40. raise Exception("key {} not in available_setting".format(key))
  41. return super().__setitem__(key, value)
  42. def get(self, key, default=None):
  43. try:
  44. return self[key]
  45. except KeyError as e:
  46. return default
  47. except Exception as e:
  48. raise e
  49. config = Config()
  50. def drag_sensitive(config):
  51. try:
  52. if isinstance(config, str):
  53. conf_dict: dict = json.loads(config)
  54. conf_dict_copy = copy.deepcopy(conf_dict)
  55. for key in conf_dict_copy:
  56. if "key" in key or "secret" in key:
  57. if isinstance(conf_dict_copy[key], str):
  58. conf_dict_copy[key] = conf_dict_copy[key][0:3] + "*" * 5 + conf_dict_copy[key][-3:]
  59. return json.dumps(conf_dict_copy, indent=4)
  60. elif isinstance(config, dict):
  61. config_copy = copy.deepcopy(config)
  62. for key in config:
  63. if "key" in key or "secret" in key:
  64. if isinstance(config_copy[key], str):
  65. config_copy[key] = config_copy[key][0:3] + "*" * 5 + config_copy[key][-3:]
  66. return config_copy
  67. except Exception as e:
  68. logger.exception(e)
  69. return config
  70. return config
  71. def load_config():
  72. global config
  73. # config_path = "./config.json"
  74. # if not os.path.exists(config_path):
  75. # logger.info("配置文件不存在,将使用config-template.json模板")
  76. # config_path = "./config-template.json"
  77. # 默认加载 config.json 或者 config-template.json
  78. environment = os.environ.get('environment', 'default') # 默认是生产环境
  79. logger.info(f"当前环境: {environment}")
  80. if environment == "test":
  81. config_path = "./config-test.json"
  82. elif environment == "production":
  83. config_path = "./config-production.json"
  84. elif environment == "dev":
  85. config_path = "./config-dev.json"
  86. elif environment == "default":
  87. config_path = "./config.json"
  88. else:
  89. logger.error("无效的环境配置,使用默认的 config-template.json")
  90. config_path = "./config-template.json"
  91. # 加载配置文件
  92. if not os.path.exists(config_path):
  93. logger.info(f"配置文件 {config_path} 不存在,将使用 config-template.json 模板")
  94. config_path = "./config-template.json"
  95. config_str = read_file(config_path)
  96. logger.debug("[INIT] config str: {}".format(drag_sensitive(config_str)))
  97. # 将json字符串反序列化为dict类型
  98. config = Config(json.loads(config_str))
  99. # override config with environment variables.
  100. # Some online deployment platforms (e.g. Railway) deploy project from github directly. So you shouldn't put your secrets like api key in a config file, instead use environment variables to override the default config.
  101. for name, value in os.environ.items():
  102. name = name.lower()
  103. if name in available_setting:
  104. logger.info("[INIT] override config by environ args: {}={}".format(name, value))
  105. try:
  106. config[name] = eval(value)
  107. except:
  108. if value == "false":
  109. config[name] = False
  110. elif value == "true":
  111. config[name] = True
  112. else:
  113. config[name] = value
  114. if config.get("debug", False):
  115. logger.setLevel(logging.DEBUG)
  116. logger.debug("[INIT] set log level to DEBUG")
  117. logger.info("[INIT] load config: {}".format(drag_sensitive(config)))
  118. def get_root():
  119. return os.path.dirname(os.path.abspath(__file__))
  120. def read_file(path):
  121. with open(path, mode="r", encoding="utf-8") as f:
  122. return f.read()
  123. def conf():
  124. return config
  125. # # global plugin config
  126. # plugin_config = {}
  127. # def write_plugin_config(pconf: dict):
  128. # """
  129. # 写入插件全局配置
  130. # :param pconf: 全量插件配置
  131. # """
  132. # global plugin_config
  133. # for k in pconf:
  134. # plugin_config[k.lower()] = pconf[k]
  135. # def pconf(plugin_name: str) -> dict:
  136. # """
  137. # 根据插件名称获取配置
  138. # :param plugin_name: 插件名称
  139. # :return: 该插件的配置项
  140. # """
  141. # return plugin_config.get(plugin_name.lower())
  142. # # 全局配置,用于存放全局生效的状态
  143. # global_config = {"admin_users": []}