# chongming-config 应用配置加载器,提供类型安全的 TOML 配置解析,支持模块级缓存。 --- ## 安装 ```bash uv pip install -e utils/config ``` 已在项目根 `pyproject.toml` 中声明为 workspace 依赖。 --- ## API ### `get_config(config_path="config.toml") -> Config` 加载并缓存全局配置。首次调用解析 TOML 文件,后续调用返回缓存对象。 ```python from chongming_config import get_config cfg = get_config() print(cfg["default"]["app"]["name"]) # "chongming" print(cfg["security"]["secret_key"]) # "your-secret-key..." print(cfg["development"]["server"]["port"]) # 8000 ``` ### `load_config(config_path) -> Config` 与 `get_config` 相同,但不使用缓存——每次都重新解析文件。 ### `get_workers_config(config_path="config/workers/config.toml") -> dict` 加载 Worker 插件注册配置,返回原始字典。 --- ## 配置结构 (TypedDict) ### 顶层 `Config` | 键 | 类型 | 说明 | | ---------------- | ----------- | --------------- | | `default` | `Default` | 应用元信息 | | `database` | `Database` | 数据库配置 | | `scheduler` | `Scheduler` | 任务调度 | | `cache` | `Cache` | 缓存配置 | | `security` | `Security` | JWT 安全 | | `development` | `Env` | 开发环境 | | `production` | `Env` | 生产环境 | | `plugins_worker` | `dict` | Worker 配置路径 | ### `Default` — 应用元信息 | 字段 | 类型 | 说明 | | ----------------- | -------------------------------------- | ---------------------------- | | `app.name` | `str` | 应用名称 | | `app.version` | `str` | 版本号 | | `app.description` | `str` | 描述 | | `app.debug` | `bool` | 调试模式 | | `env` | `Literal["development", "production"]` | 当前环境 | | `prefix` | `str` | API 路由前缀,如 `"/api/v1"` | | `upload_path` | `str` | 文件上传目录 | ### `Security` — 安全配置 | 字段 | 类型 | 说明 | | ------------ | ----- | ------------------------------ | | `secret_key` | `str` | JWT 签名密钥 | | `algorithm` | `str` | JWT 签名算法(默认 `"HS256"`) | ### `Server` — 服务器配置 | 字段 | 类型 | 说明 | | ------------ | ------ | -------- | | `host` | `str` | 监听地址 | | `port` | `int` | 监听端口 | | `reload` | `bool` | 热重载 | | `access_log` | `bool` | 访问日志 | ### `Database` — 数据库配置 | 字段 | 类型 | 说明 | | ------------------ | ------------------------------------------ | ------------ | | `type` | `Literal["sqlite", "mysql", "postgresql"]` | 数据库类型 | | `url` | `str` | 连接 URL | | `generate_schemas` | `bool` | 是否自动建表 | --- ## 使用模式 ```python from chongming_config import get_config, get_workers_config # 获取全局配置 cfg = get_config() env = cfg["default"]["env"] server_cfg = cfg[env]["server"] # 获取 Worker 注册列表 workers = get_workers_config() for w in workers["workers"]: print(f"插件: {w['type']}, 副本: {w['count']}") ``` --- ## 依赖 - `tomli` / `tomllib` — TOML 解析(Python 版本自适应) - `typing-extensions` — TypedDict 支持