This commit implements a complete migration from JSON-based configuration to .env environment variables, providing better security and flexibility. Key Changes: - Add python-dotenv dependency for environment variable support - Create config/env_loader.py with type conversion utilities - Add from_env() class methods to all config dataclasses - Update ConfigLoader to prioritize environment variables - Add save_to_env() method for .env file management - Implement database connection factory pattern - Add base DAO and connection classes for better abstraction - Support both SQL Server and MySQL with unified interface - Create migration script (scripts/migrate_to_env.py) - Update GUI to read/write .env files - Add comprehensive migration documentation New Files: - config/env_loader.py - Environment variable loader - db/base_connection.py - Base database connection interface - db/base_dao.py - Base DAO with common utilities - db/connection_factory.py - Factory for creating connections - db/mysql_connection.py - MySQL-specific connection - db/sqlserver_connection.py - SQL Server-specific connection - db/table_name_converter.py - SQL dialect converter - scripts/migrate_to_env.py - Configuration migration tool - docs/ENV_MIGRATION.md - Complete migration guide - .env.example - Environment variable template Testing: - Verified MySQL connection (8.0.44) - Tested all DAO operations - Confirmed 150 tables accessible - Validated configuration loading Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
128 lines
3.1 KiB
Python
128 lines
3.1 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
配置管理器
|
|
|
|
负责加载、保存和管理用户配置。
|
|
支持从环境变量和 .env 文件加载配置。
|
|
"""
|
|
import os
|
|
from typing import TYPE_CHECKING
|
|
from config.loader import ConfigLoader
|
|
from config.schema import AppConfig
|
|
from config.defaults import DEFAULT_SETTINGS_DICT
|
|
|
|
# 类型提示时导入,避免循环引用
|
|
if TYPE_CHECKING:
|
|
from config.schema import ERPConfig, DatabaseConfig, PathConfig, ExtractionConfig
|
|
|
|
|
|
class ConfigManager:
|
|
"""配置管理器"""
|
|
|
|
def __init__(self, config_file: str = "config/user_settings.json", use_env: bool = True):
|
|
"""
|
|
初始化配置管理器
|
|
|
|
Args:
|
|
config_file: 配置文件路径(向后兼容)
|
|
use_env: 是否使用环境变量,默认为 True
|
|
"""
|
|
self.config_file = config_file
|
|
self.use_env = use_env
|
|
self.config: AppConfig = ConfigLoader.load(config_file, use_env=use_env)
|
|
|
|
# 验证配置
|
|
errors = self.config.validate()
|
|
if errors:
|
|
print("配置验证失败:")
|
|
for error in errors:
|
|
print(f" - {error}")
|
|
|
|
def save(self) -> bool:
|
|
"""
|
|
保存配置到文件
|
|
|
|
如果使用环境变量,则保存到 .env 文件
|
|
否则保存到 JSON 文件(向后兼容)
|
|
|
|
Returns:
|
|
保存是否成功
|
|
"""
|
|
if self.use_env:
|
|
return ConfigLoader.save_to_env(self.config, ".env")
|
|
else:
|
|
return ConfigLoader.save(self.config, self.config_file)
|
|
|
|
def get(self, key: str, default=None):
|
|
"""
|
|
获取配置项
|
|
|
|
支持点号分隔的路径,如 "erp.url"
|
|
|
|
Args:
|
|
key: 配置键
|
|
default: 默认值
|
|
|
|
Returns:
|
|
配置值
|
|
"""
|
|
keys = key.split(".")
|
|
value = self.config
|
|
|
|
try:
|
|
for k in keys:
|
|
value = getattr(value, k)
|
|
return value
|
|
except (AttributeError, TypeError):
|
|
return default
|
|
|
|
def set(self, key: str, value) -> None:
|
|
"""
|
|
设置配置项
|
|
|
|
支持点号分隔的路径,如 "erp.url"
|
|
|
|
Args:
|
|
key: 配置键
|
|
value: 配置值
|
|
"""
|
|
keys = key.split(".")
|
|
obj = self.config
|
|
|
|
# 导航到父对象
|
|
for k in keys[:-1]:
|
|
obj = getattr(obj, k)
|
|
|
|
# 设置最终值
|
|
setattr(obj, keys[-1], value)
|
|
|
|
def reset_to_defaults(self) -> None:
|
|
"""重置为默认配置"""
|
|
self.config = AppConfig.from_env() # 重新从环境变量加载默认配置
|
|
self.save()
|
|
|
|
@property
|
|
def erp(self):
|
|
"""获取 ERP 配置"""
|
|
return self.config.erp
|
|
|
|
@property
|
|
def database(self):
|
|
"""获取数据库配置"""
|
|
return self.config.database
|
|
|
|
@property
|
|
def paths(self):
|
|
"""获取路径配置"""
|
|
return self.config.paths
|
|
|
|
@property
|
|
def extraction(self):
|
|
"""获取提取配置"""
|
|
return self.config.extraction
|
|
|
|
|
|
# 为了向后兼容,保留旧版本的导入
|
|
DEFAULT_SETTINGS = DEFAULT_SETTINGS_DICT
|