YamlLoader.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/12/22 10:44
  5. import os, re
  6. import yaml
  7. regex = re.compile(r'^\$\{(?P<ENV>[A-Z_\-]+:)?(?P<VAL>[\w.]+)}$')
  8. class YamlConfig:
  9. def __init__(self, config):
  10. self.config = config
  11. def get(self, key: str):
  12. return YamlConfig(self.config.get(key))
  13. def getValueAsString(self, key: str):
  14. try:
  15. match = regex.match(self.config[key])
  16. group = match.groupdict()
  17. if group['ENV'] is not None:
  18. env = group['ENV'][:-1]
  19. return os.getenv(env, group['VAL'])
  20. return None
  21. except:
  22. return self.config[key]
  23. def getValueAsInt(self, key: str):
  24. try:
  25. match = regex.match(self.config[key])
  26. group = match.groupdict()
  27. if group['ENV'] is not None:
  28. env = group['ENV'][:-1]
  29. return int(os.getenv(env, group['VAL']))
  30. return 0
  31. except:
  32. return int(self.config[key])
  33. def getValueAsBool(self, key: str):
  34. try:
  35. match = regex.match(self.config[key])
  36. group = match.groupdict()
  37. if group['ENV'] is not None:
  38. env = group['ENV'][:-1]
  39. return bool(os.getenv(env, group['VAL']))
  40. return False
  41. except:
  42. return bool(self.config[key])
  43. def readYaml(path: str = 'application.yml', profile: str = None) -> YamlConfig:
  44. if os.path.exists(path):
  45. with open(path) as fd:
  46. conf = yaml.load(fd, Loader=yaml.FullLoader)
  47. if profile is not None:
  48. result = path.split('.')
  49. profiledYaml = f'{result[0]}-{profile}.{result[1]}'
  50. if os.path.exists(profiledYaml):
  51. with open(profiledYaml) as fd:
  52. conf.update(yaml.load(fd, Loader=yaml.FullLoader))
  53. return YamlConfig(conf)
  54. # res = readYaml()
  55. # mysqlConf = res.get('mysql')
  56. # print(mysqlConf)
  57. # print(res.getValueAsString("host"))
  58. # mysqlYaml = mysqlConf.getValueAsString("host")
  59. # print(mysqlYaml)
  60. # host = mysqlYaml.get("host").split(':')[-1][:-1]
  61. # port = mysqlYaml.get("port").split(':')[-1][:-1]
  62. # username = mysqlYaml.get("username").split(':')[-1][:-1]
  63. # password = mysqlYaml.get("password").split(':')[-1][:-1]
  64. # mysql_db = mysqlYaml.get("db").split(':')[-1][:-1]
  65. # print(host,port,username,password)