Browse Source

update 优化配置加载

YueYunyun 3 months ago
parent
commit
5ad8d91706

+ 1 - 1
SERVER/app/application-dev.yml

@@ -1,5 +1,5 @@
 app:
 app:
-  name: Smart Question Bank
+  name: 智能题库学习系统
   version: 1.0.1
   version: 1.0.1
   debug: true
   debug: true
 
 

+ 1 - 1
SERVER/app/application-prod.yml

@@ -1,5 +1,5 @@
 app:
 app:
-  name: Smart Question Bank
+  name: 智能题库学习系统
   version: 1.0.0
   version: 1.0.0
   debug: false
   debug: false
 
 

+ 12 - 0
SERVER/app/config/config_env_mapping.py

@@ -0,0 +1,12 @@
+"""环境变量映射配置"""
+
+ENV_MAPPING = {
+    'APP_NAME': 'app.name',
+    'APP_VERSION': 'app.version',
+    'APP_DEBUG': 'app.debug',
+    'DB_HOST': 'database.host',
+    'DB_PORT': 'database.port',
+    'DB_USER': 'database.user',
+    'DB_PASSWORD': 'database.password',
+    'DB_NAME': 'database.name',
+}

+ 37 - 18
SERVER/app/config/loader_config.py

@@ -2,7 +2,9 @@ import os, yaml, datetime
 from typing import Any, List, Callable
 from typing import Any, List, Callable
 from watchdog.observers import Observer
 from watchdog.observers import Observer
 from watchdog.events import FileSystemEventHandler
 from watchdog.events import FileSystemEventHandler
+from dotenv import load_dotenv
 from .config import Config
 from .config import Config
+from .config_env_mapping import ENV_MAPPING
 
 
 
 
 class ConfigReloadHandler(FileSystemEventHandler):
 class ConfigReloadHandler(FileSystemEventHandler):
@@ -21,18 +23,6 @@ class ConfigLoader:
     _instance = None
     _instance = None
     _observers = []
     _observers = []
 
 
-    # 环境变量映射配置
-    ENV_MAPPING = {
-        'APP_NAME': 'app.name',
-        'APP_VERSION': 'app.version',
-        'APP_DEBUG': 'app.debug',
-        'DB_HOST': 'database.host',
-        'DB_PORT': 'database.port',
-        'DB_USER': 'database.user',
-        'DB_PASSWORD': 'database.password',
-        'DB_NAME': 'database.name',
-    }
-
     def __new__(cls):
     def __new__(cls):
         if cls._instance is None:
         if cls._instance is None:
             cls._instance = super().__new__(cls)
             cls._instance = super().__new__(cls)
@@ -41,7 +31,7 @@ class ConfigLoader:
 
 
     def _load_env_vars(self, config: Config) -> Config:
     def _load_env_vars(self, config: Config) -> Config:
         """加载环境变量配置"""
         """加载环境变量配置"""
-        for env_key, config_path in self.ENV_MAPPING.items():
+        for env_key, config_path in ENV_MAPPING.items():
             value = os.getenv(env_key)
             value = os.getenv(env_key)
             if value is None:
             if value is None:
                 continue
                 continue
@@ -152,16 +142,26 @@ class ConfigLoader:
         self._config = Config()
         self._config = Config()
         self._callbacks: List[Callable] = []
         self._callbacks: List[Callable] = []
 
 
+        # 获取当前文件所在目录并保存到类变量
+        self._current_dir = os.path.dirname(
+            os.path.dirname(os.path.abspath(__file__)))
+        load_dotenv(os.path.join(self._current_dir, '.env'))
+        # print(f"配置当前目录为:{self._current_dir}")
+
         # 1. 加载默认值(通过Config类初始化)
         # 1. 加载默认值(通过Config类初始化)
 
 
         # 2. 加载通用配置
         # 2. 加载通用配置
         self._config.update_from_dict(
         self._config.update_from_dict(
-            self._load_yaml_config('SERVER/app/application.yml'))
+            self._load_yaml_config(
+                os.path.join(self._current_dir, 'application.yml')))
 
 
         # 3. 加载指定环境配置
         # 3. 加载指定环境配置
-        env = os.getenv('ENV', 'dev')
-        self._config.update_from_dict(
-            self._load_yaml_config(f'SERVER/app/application-{env}.yml'))
+        env = os.getenv('ENV')
+        print(f"当前环境:{env}")
+        if env:
+            self._config.update_from_dict(
+                self._load_yaml_config(
+                    os.path.join(self._current_dir, f'application-{env}.yml')))
 
 
         # 4. 最后加载环境变量(最高优先级)
         # 4. 最后加载环境变量(最高优先级)
         self._config = self._load_env_vars(self._config)
         self._config = self._load_env_vars(self._config)
@@ -173,13 +173,32 @@ class ConfigLoader:
         """启动配置文件监控"""
         """启动配置文件监控"""
         event_handler = ConfigReloadHandler(self.reload_config)
         event_handler = ConfigReloadHandler(self.reload_config)
         observer = Observer()
         observer = Observer()
-        observer.schedule(event_handler, path='SERVER/app/', recursive=False)
+
+        # 只监控application.yml和application-{env}.yml文件
+        env = os.getenv('ENV', 'dev')
+        config_files = [
+            os.path.join(self._current_dir, 'application.yml'),
+            os.path.join(self._current_dir, f'application-{env}.yml')
+        ]
+
+        for config_file in config_files:
+            if os.path.exists(config_file):
+                observer.schedule(event_handler,
+                                  path=os.path.dirname(config_file),
+                                  recursive=False)
+
         observer.start()
         observer.start()
         self._observers.append(observer)
         self._observers.append(observer)
 
 
     def reload_config(self):
     def reload_config(self):
         """重新加载配置"""
         """重新加载配置"""
+        # 1. 重新加载配置文件
         self._load_config()
         self._load_config()
+
+        # 2. 重新加载环境变量(确保覆盖配置文件)
+        self._config = self._load_env_vars(self._config)
+
+        # 3. 触发回调
         for callback in self._callbacks:
         for callback in self._callbacks:
             callback()
             callback()
 
 

+ 1 - 1
SERVER/app/main.py

@@ -11,7 +11,7 @@ from SERVER.app.logger import logger
 
 
 
 
 def main():
 def main():
-    logger.info(f"正在启动应用 [{config.app.name}]")
+    logger.info(f"正在启动应用 [{config.app.name}({config.app.version})]")
     logger.debug(f"调试模式: {config.app.debug}")
     logger.debug(f"调试模式: {config.app.debug}")
 
 
     # logger.info(f"加载配置文件:\n{config.to_string()}")
     # logger.info(f"加载配置文件:\n{config.to_string()}")

+ 0 - 7
application-dev.yml

@@ -1,7 +0,0 @@
-debug: true
-database:
-  uri: mysql://localhost:3306/dev_db
-  pool_size: 10
-api:
-  url: http://localhost:8000
-  timeout: 60

+ 1 - 1
requirements.txt

@@ -3,4 +3,4 @@ pydantic>=2.0.0
 pydantic-settings>=2.0.0
 pydantic-settings>=2.0.0
 watchdog>=3.0.0
 watchdog>=3.0.0
 loguru>=0.7.0
 loguru>=0.7.0
-
+python-dotenv>=1.0.0