YamlLoader.py 2.3 KB

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