Skip to main content

高质量的 Python 配置管理库 - 基于 Provider 模式,支持多种配置源

Project description

YAI Nexus Configuration

🚀 高质量的 Python 配置管理库 - 基于 Provider 模式,支持多种配置源

Python License Version

🎬 快速上手 (Hello, World!)

这是体验 yai-nexus-configuration 核心功能的最快方式。我们将通过一个完整的、可运行的示例,展示“定义 -> 创建 -> 注册 -> 获取”的黄金路径。

1. 项目结构

首先,请像这样组织您的项目文件:

your-project/
├── configs/
│   └── DEFAULT_GROUP/
│       └── app_config.json
└── main.py

2. 创建配置文件

configs/DEFAULT_GROUP/ 目录下创建一个名为 app_config.json 的文件,内容如下:

{
  "database_url": "sqlite:///./test.db",
  "retries": 5,
  "api_key": "a-secret-key-from-environment"
}

提示: 在未来的版本中,我们将支持 ${VAR} 格式的环境变量自动替换,以增强安全性。

3. 编写 Python 代码 (main.py)

现在,创建 main.py 并复制以下代码。它包含了使用本库的所有核心步骤。

from yai_nexus_configuration import NexusConfig, nexus_config, NexusConfigManager

# 步骤 1: 定义一个与 JSON 结构匹配的配置类
# @nexus_config 装饰器将类与配置文件关联起来
@nexus_config(data_id="app_config.json", group="DEFAULT_GROUP")
class AppConfig(NexusConfig):
    database_url: str
    retries: int = 3  # 您可以提供默认值
    api_key: str

# 步骤 2: 使用工厂方法创建管理器
# `with` 语句能确保资源被正确管理和释放
with NexusConfigManager.with_file(base_path="configs") as manager:
    # 步骤 3: 向管理器注册您的配置类
    manager.register(AppConfig)

    # 步骤 4: 从管理器中获取类型安全的配置实例
    config = manager.get_config(AppConfig)

# 步骤 5: 像使用普通对象一样使用您的配置
print(f"数据库 URL: {config.database_url}")
print(f"重试次数: {config.retries}")
print(f"API 密钥: {config.api_key}")

# 运行此脚本,您将看到从文件中加载并经过验证的配置!

效果: 这个“黄金路径”示例清晰地展示了本库的核心设计思想,能帮助您快速上手,避免常见的使用陷阱。


✨ 主要特性

  • 🎯 简洁优雅的 API - 采用工厂模式,一行代码创建管理器
  • 🔒 线程安全 - 所有操作都是线程安全的,适用于多线程环境
  • 🔄 自动配置更新 - 实时监听配置源变更,自动更新本地配置
  • 🧩 可扩展架构 - 基于 Provider 模式,轻松支持新的配置源
  • 类型安全 - 完整的类型提示支持,基于 Pydantic 数据验证
  • 📦 零依赖冲突 - 精心设计的依赖管理,避免版本冲突

🏗️ 架构设计

YAI Nexus Configuration 采用了经过深度思考的 方案 E(工厂模式) 架构:

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   用户代码      │────│  NexusConfigManager    │────│  ConfigStore    │
│                 │    │  (工厂 + 管理)    │    │  (线程安全存储)  │
└─────────────────┘    └──────────┬───────┘    └─────────────────┘
                                  │
                                  ▼
                       ┌──────────────────┐
                       │ AbstractProvider │
                       │    (抽象层)       │
                       └─────────┬────────┘
                                 │
                    ┌────────────┴────────────┐
                    ▼                         ▼
            ┌──────────────┐        ┌──────────────┐
            │ NacosProvider│        │ 未来的Provider│
            │              │        │ (Apollo等)   │
            └──────────────┘        └──────────────┘

核心优势

  • 高内聚,低耦合: Provider 抽象层完全隔离了配置源实现
  • 面向接口编程: 核心逻辑只依赖抽象接口,便于测试和扩展
  • 工厂模式: 提供简洁的创建接口,隐藏复杂的初始化逻辑
  • 单一职责: 每个组件都有明确的职责边界

🔧 支持的配置源

配置源 状态 工厂方法 说明
Nacos ✅ 已支持 NexusConfigManager.with_nacos() 阿里巴巴开源的配置中心
Apollo 🚧 规划中 NexusConfigManager.with_apollo() 携程开源的配置中心
Etcd 🚧 规划中 NexusConfigManager.with_etcd() 分布式键值存储
本地文件 ✅ 已支持 NexusConfigManager.with_file() 本地 JSON/YAML/ENV 文件

📖 详细文档

文件配置使用

文件提供者可以根据文件扩展名(.json.yaml)自动选择解析器。

1. 定义多个配置类

from yai_nexus_configuration import NexusConfigManager, NexusConfig, nexus_config

# JSON 配置
@nexus_config(data_id="app.json", group="DEFAULT_GROUP")
class AppConfig(NexusConfig):
    app_name: str
    debug: bool

# YAML 配置 (需要安装 PyYAML)
@nexus_config(data_id="database.yaml", group="PROD")
class DbConfig(NexusConfig):
    host: str
    port: int

2. 使用同一个管理器

# 只需要一个管理器实例
with NexusConfigManager.with_file(
    base_path="configs",        # 配置文件根目录
    watch_interval=1.0,         # 文件监听间隔(秒)
) as manager:
    
    # 你的文件结构:
    # configs/
    # ├── DEFAULT_GROUP/
    # │   └── app.json
    # └── PROD/
    #     └── database.yaml

    # 批量注册
    manager.register(AppConfig, DbConfig)
    
    # 获取配置
    app_config = manager.get_config(AppConfig)
    db_config = manager.get_config(DbConfig)
    
    print(f"应用: {app_config.app_name}, 数据库主机: {db_config.host}")

Nacos 配置使用

# 创建管理器(建议从环境变量获取敏感信息)
manager = NexusConfigManager.with_nacos(
    server_addresses=os.environ.get("NACOS_SERVER_ADDR"),
    namespace=os.environ.get("NACOS_NAMESPACE"),
    username=os.environ.get("NACOS_USERNAME"),
    password=os.environ.get("NACOS_PASSWORD")
)

# 查看 examples/nacos_example.py 获取最佳实践

管理器使用

# 创建管理器(以 Nacos 为例)
manager = NexusConfigManager.with_nacos(
    server_addresses="localhost:8848",
    namespace="production",
    username="admin",
    password="admin123"
)

# 批量注册配置
configs = [DatabaseConfig, RedisConfig, AppConfig]
for config_class in configs:
    manager.register(config_class)

# 获取配置(类型安全)
app_config: AppConfig = manager.get_config(AppConfig)

# 检查管理器状态
info = manager.get_manager_info()
print(f"已注册 {info['registered_configs']} 个配置")

# 优雅关闭
manager.close()

上下文管理器

# 推荐使用 with 语句,自动管理资源
with NexusConfigManager.with_nacos("localhost:8848") as manager:
    manager.register(AppConfig)
    
    app_config = manager.get_config(AppConfig)
    print(f"App: {app_config.app_name}")
    
# 管理器自动关闭,清理所有资源

配置实时更新

# 配置更新是自动的!
manager.register(AppConfig)

# 在 Nacos 控制台修改配置后...
app_config = manager.get_config(AppConfig)  # 自动获取最新配置

# 也支持手动刷新
updated_config = manager.reload_config(AppConfig)

🧪 扩展新的配置源

YAI Nexus Configuration 的设计让添加新配置源变得非常简单:

from yai_nexus_configuration.providers import AbstractProvider

class MyCustomProvider(AbstractProvider):
    def __init__(self, config_url: str):
        super().__init__("MyCustom")
        self.config_url = config_url
    
    def connect(self):
        # 实现连接逻辑
        pass
    
    def get_config(self, data_id: str, group: str) -> str:
        # 实现配置获取逻辑
        pass
    
    def watch_config(self, data_id: str, group: str, callback):
        # 实现配置监听逻辑
        pass
    
    # ... 其他必须实现的方法

# 在 NexusConfigManager 中添加工厂方法
@classmethod
def with_my_custom(cls, config_url: str) -> "NexusConfigManager":
    provider = MyCustomProvider(config_url)
    return cls(provider)

🔍 错误处理

from yai_nexus_configuration import (
    ConfigNotRegisteredError,
    ConfigValidationError,
    ProviderConnectionError
)

try:
    manager = NexusConfigManager.with_nacos("localhost:8848")
    manager.register(DatabaseConfig)
    db_config = manager.get_config(DatabaseConfig)
    
except ProviderConnectionError as e:
    print(f"无法连接到配置源: {e}")
    
except ConfigValidationError as e:
    print(f"配置数据验证失败: {e}")
    
except ConfigNotRegisteredError as e:
    print(f"配置未注册: {e}")

📦 安装

基础安装

# 最小安装(包含文件和 YAML 支持)
pip install yai-nexus-configuration

功能扩展安装

# 安装 Nacos 支持
pip install yai-nexus-configuration[nacos]

# 安装所有功能
pip install yai-nexus-configuration[all]

开发环境安装

# 克隆项目
git clone https://github.com/yai-nexus/yai-nexus-configuration.git
cd yai-nexus-configuration

# 安装开发依赖
pip install -r requirements.txt

# 或者使用 pip 安装开发模式
pip install -e ".[dev]"

快速开始

# 运行文件配置示例(无外部依赖)
python3 examples/file_example.py

# 运行 Nacos 示例
# 1. 确保 Nacos 服务正在运行,并已按示例文件中的说明创建配置
# 2. 设置环境变量:
#    export NACOS_SERVER_ADDR="your_nacos_address:8848"
#    export NACOS_NAMESPACE="your_namespace" # (可选)
#    export NACOS_USERNAME="nacos"           # (可选)
#    export NACOS_PASSWORD="nacos"         # (可选)
# 3. 运行脚本:
python3 examples/nacos_example.py

🧑‍💻 开发

运行测试

# 单元测试
pytest tests/

# 覆盖率测试
pytest --cov=src/yai_nexus_configuration tests/

🎯 设计哲学

YAI Nexus Configuration 的设计遵循以下原则:

  1. 简洁胜过复杂 - API 设计力求简洁直观
  2. 显式胜过隐式 - 避免魔法方法,所有行为都是可预测的
  3. 面向接口编程 - 通过抽象接口实现高度解耦
  4. 失败快速暴露 - 配置错误在启动时就会被发现,而不是运行时
  5. 类型安全第一 - 完整的类型提示,让 IDE 和工具更好地帮助开发

🤝 贡献

我们欢迎任何形式的贡献!

  • 🐛 报告 Bug
  • 💡 提出新功能建议
  • 📖 改进文档
  • 🔧 提交代码改进

请查看 CONTRIBUTING.md 了解详细的贡献指南。

📜 许可证

本项目采用 MIT 许可证 - 详见 LICENSE 文件。

🙏 致谢

  • Pydantic - 提供优秀的数据验证能力
  • nacos-sdk-python - Nacos Python SDK
  • 所有为这个项目贡献想法和代码的开发者们

⭐ 如果这个项目对您有帮助,请给我们一个 Star!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

yai_nexus_configuration-0.1.1.tar.gz (25.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

yai_nexus_configuration-0.1.1-py3-none-any.whl (25.8 kB view details)

Uploaded Python 3

File details

Details for the file yai_nexus_configuration-0.1.1.tar.gz.

File metadata

  • Download URL: yai_nexus_configuration-0.1.1.tar.gz
  • Upload date:
  • Size: 25.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for yai_nexus_configuration-0.1.1.tar.gz
Algorithm Hash digest
SHA256 4231370e2a2dafcb41cede3bf9c0d2a93a4ed97d9f55776371ddfa2285e06716
MD5 1e70e17d0b5437cd3e03ed4fe6e66b5f
BLAKE2b-256 d0149928531597735e791cd8fd32953b62edbd77ae3d79c3afbd12a5dceafc64

See more details on using hashes here.

Provenance

The following attestation bundles were made for yai_nexus_configuration-0.1.1.tar.gz:

Publisher: pypi-publish.yml on yai-nexus/yai-nexus-configuration

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file yai_nexus_configuration-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for yai_nexus_configuration-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b5369c74f58deb59b50458cae121279620bc967bbe51662ee8418a89a8380267
MD5 9c642ab276808e3c4a831f934fe767eb
BLAKE2b-256 ebd05ee4abf2606273f7ea0032b0ddc6d265f8540308118fe17322cb787c7216

See more details on using hashes here.

Provenance

The following attestation bundles were made for yai_nexus_configuration-0.1.1-py3-none-any.whl:

Publisher: pypi-publish.yml on yai-nexus/yai-nexus-configuration

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page