123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- from pydantic_settings import BaseSettings
- from .config_app import AppConfig
- from .config_database import DatabaseConfig
- from .config_logging import LoggingConfig
- class Config(BaseSettings):
- app: AppConfig = AppConfig()
- database: DatabaseConfig = DatabaseConfig()
- logging: LoggingConfig = LoggingConfig()
- class Config:
- env_prefix = ''
- env_nested_delimiter = '__'
- case_sensitive = False
- def __init__(self, **data):
- super().__init__(**data)
- # 确保logging配置被正确初始化
- if not hasattr(self, 'logging'):
- self.logging = LoggingConfig()
- def to_string(self, indent: int = 0) -> str:
- """将配置转换为字符串"""
- indent_str = ' ' * indent
- result = []
- for field_name, field_value in self.__dict__.items():
- if hasattr(field_value, 'to_string'):
- result.append(
- f"{indent_str}{field_name}:\n{field_value.to_string(indent + 4)}"
- )
- else:
- result.append(f"{indent_str}{field_name}: {field_value}")
- return '\n'.join(result)
- def _update_config_section(self, config_dict: dict, section: str,
- config_class: type) -> None:
- """
- 更新配置的某个部分
-
- Args:
- config_dict: 包含配置项的字典
- section: 配置部分名称
- config_class: 配置类
- """
- if section in config_dict:
- setattr(
- self, section,
- config_class(
- **{
- k: v
- for k, v in config_dict[section].items()
- if k in config_class.model_fields
- }))
- def update_from_dict(self,
- config_dict: dict,
- partial: bool = False) -> None:
- """
- 从字典更新配置
-
- Args:
- config_dict: 包含配置项的字典
- partial: 是否部分更新,默认为False
- """
- try:
- self._update_config_section(config_dict, 'app', AppConfig)
- self._update_config_section(config_dict, 'database',
- DatabaseConfig)
- self._update_config_section(config_dict, 'logging', LoggingConfig)
- except Exception as e:
- raise ValueError(f"配置更新失败: {e}")
|