71 lines
1.7 KiB
Python
71 lines
1.7 KiB
Python
import os
|
|
import yaml
|
|
from typing import Dict, Any
|
|
from pydantic import BaseModel
|
|
|
|
|
|
class DatabaseConfig(BaseModel):
|
|
"""数据库配置"""
|
|
host: str
|
|
port: int = 3306
|
|
username: str
|
|
password: str
|
|
database: str
|
|
charset: str = "utf8mb4"
|
|
|
|
|
|
class AppConfig(BaseModel):
|
|
"""应用配置"""
|
|
name: str
|
|
debug: bool = False
|
|
host: str = "localhost"
|
|
port: int = 12315
|
|
database: DatabaseConfig
|
|
|
|
|
|
class Settings:
|
|
"""配置管理器"""
|
|
|
|
def __init__(self):
|
|
self._config: AppConfig = None
|
|
self._env = os.getenv("ENVIRONMENT", "development")
|
|
self.load_config()
|
|
|
|
def load_config(self):
|
|
"""加载配置文件"""
|
|
config_file = f"config/{self._env}.yaml"
|
|
|
|
if not os.path.exists(config_file):
|
|
raise FileNotFoundError(f"配置文件不存在: {config_file}")
|
|
|
|
with open(config_file, 'r', encoding='utf-8') as f:
|
|
config_data = yaml.safe_load(f)
|
|
|
|
# 解析数据库配置
|
|
db_config = DatabaseConfig(**config_data['database'])
|
|
|
|
# 解析应用配置
|
|
app_data = config_data['app']
|
|
app_data['database'] = db_config
|
|
|
|
self._config = AppConfig(**app_data)
|
|
|
|
@property
|
|
def config(self) -> AppConfig:
|
|
"""获取配置"""
|
|
return self._config
|
|
|
|
@property
|
|
def environment(self) -> str:
|
|
"""获取当前环境"""
|
|
return self._env
|
|
|
|
@property
|
|
def database_url(self) -> str:
|
|
"""获取数据库连接URL"""
|
|
db = self._config.database
|
|
return f"mysql+pymysql://{db.username}:{db.password}@{db.host}:{db.port}/{db.database}?charset={db.charset}"
|
|
|
|
|
|
# 全局配置实例
|
|
settings = Settings() |