-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
115 lines (88 loc) · 2.74 KB
/
config.py
File metadata and controls
115 lines (88 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""
配置管理模块
从 config.yaml 加载配置,提供类型安全的访问接口
"""
from dataclasses import dataclass, field
from pathlib import Path
from typing import Literal
import yaml
@dataclass
class ServerConfig:
"""服务配置"""
host: str = "0.0.0.0"
port: int = 7860
@dataclass
class DownloadConfig:
"""下载配置"""
base_dir: str = "./downloads"
max_concurrent: int = 3
default_quality: str = "best"
@dataclass
class LoggingConfig:
"""日志配置"""
level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
file: str = "./logs/app.log"
max_size: str = "10MB"
backup_count: int = 5
def get_max_bytes(self) -> int:
"""将 max_size 转换为字节数"""
size = self.max_size.upper()
if size.endswith("MB"):
return int(size[:-2]) * 1024 * 1024
if size.endswith("KB"):
return int(size[:-2]) * 1024
return int(size)
@dataclass
class UserConfig:
"""用户配置"""
username: str
password: str
role: Literal["admin", "user"] = "user"
@dataclass
class AppConfig:
"""应用配置"""
server: ServerConfig = field(default_factory=ServerConfig)
download: DownloadConfig = field(default_factory=DownloadConfig)
logging: LoggingConfig = field(default_factory=LoggingConfig)
users: list[UserConfig] = field(default_factory=list)
# Session 密钥,用于 NiceGUI app.storage.user;未设置时从环境变量 VIDEOFETCHER_STORAGE_SECRET 读取
storage_secret: str | None = None
def load_config(config_path: str = "config.yaml") -> AppConfig:
"""
加载配置文件
Args:
config_path: 配置文件路径
Returns:
AppConfig 实例
"""
path = Path(config_path)
if not path.exists():
raise FileNotFoundError(f"配置文件不存在: {config_path}")
with open(path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
# 解析各配置块
server = ServerConfig(**data.get("server", {}))
download = DownloadConfig(**data.get("download", {}))
logging_cfg = LoggingConfig(**data.get("logging", {}))
# 解析用户列表
users = [UserConfig(**u) for u in data.get("users", [])]
return AppConfig(
server=server,
download=download,
logging=logging_cfg,
users=users,
storage_secret=data.get("storage_secret"),
)
# 全局配置实例(延迟加载)
_config: AppConfig | None = None
def get_config() -> AppConfig:
"""获取全局配置实例"""
global _config
if _config is None:
_config = load_config()
return _config
def reload_config() -> AppConfig:
"""重新加载配置"""
global _config
_config = load_config()
return _config