config.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # -*- coding: utf-8 -*-
  2. # @Author : YY
  3. import os
  4. from typing import Dict
  5. from flask import Flask
  6. import yaml
  7. from ..utils.base import DictUtil
  8. CONFIG_CACHE = dict()
  9. class RuoYiConfigLoader(object):
  10. pname = "config"
  11. name = "app.yml"
  12. name_tmpl = "app-{}.yml"
  13. def __init__(self, root):
  14. self._root = root
  15. self._raw_data = {}
  16. config_file = self._generate_main_config()
  17. self.load_config(config_file)
  18. self.load_config_from_cache()
  19. def load_config_from_cache(self):
  20. '''
  21. 从缓存配置env配置中加载配置
  22. '''
  23. env = self.cache.get("ruoyi.env")
  24. if env is not None:
  25. config_file = os.path.join(self._root, self.pname, self.name_tmpl.format(env))
  26. if not os.path.exists(config_file):
  27. raise FileNotFoundError(f"Config file {config_file} not found")
  28. self.load_config(config_file)
  29. def _generate_main_config(self) -> str:
  30. '''
  31. 生成配置文件
  32. Returns:
  33. str: 配置文件路径
  34. '''
  35. config_path = os.path.join(self._root, self.pname)
  36. config_file = os.path.join(config_path, self.name)
  37. if not os.path.exists(config_path):
  38. os.mkdir(config_path)
  39. return config_file
  40. def load_config(self, file):
  41. '''
  42. 加载配置文件参数
  43. '''
  44. with open(file, 'r') as f:
  45. config_obj = yaml.load(f, Loader=yaml.FullLoader)
  46. self._raw_data.update(config_obj)
  47. data = DictUtil.recurive_key(config_obj)
  48. flatten_data = DictUtil.flatten(data)
  49. formated_data = DictUtil.format_value(flatten_data)
  50. CONFIG_CACHE.update(formated_data)
  51. @property
  52. def cache(self) -> Dict:
  53. """
  54. 缓存配置
  55. Returns:
  56. Dict: 缓存配置
  57. """
  58. return CONFIG_CACHE
  59. def set_app(self,app:Flask):
  60. """
  61. 关联flask应用
  62. Args:
  63. app (Flask): flask应用
  64. """
  65. config = self._raw_data.get("flask",{})
  66. ruoyi_config = self._raw_data.get("ruoyi",{})
  67. host = ruoyi_config.get("host","127.0.0.1")
  68. port = ruoyi_config.get("port",9000)
  69. config.update({"SERVER_NAME":f"{host}:{port}"})
  70. config = DictUtil.upper_key(config)
  71. app.config.update(config)