跳转到主要内容

用于从各种来源创建配置对象的Python库,包括文件、环境变量和Azure Key Vault。

项目描述

essex-config

essex-config 是一个用于创建配置对象的Python库,可以从各种来源读取,包括文件、环境变量和Azure Key Vault。

安装

使用pip安装essex-config库

pip install essex-config

基本用法

为连接到客户数据库创建配置对象

from pydantic import BaseModel, Field
from essex_config import config

@config()
class CustomerDatabase(BaseModel):
    """Configuration for connecting to the Customer Database"""
    host: str = Field(default="127.0.0.1", description="DB connection host")
    port: int = Field(description="DB connection port")
    password: str = Field(description="DB connection password")

if __name__ == "__main__":
    config = CustomerDatabase.load_config()
    print(config)

当执行CustomerDatabase.load_config()时,值将从环境变量或默认值中填充。

高级用法

来源

使用@config装饰器中的sources参数添加不同的配置数据来源

from essex_config.sources import EnvSource

@config(sources=[EnvSource()])
class CustomerDatabase(BaseModel):
    ...

essex-config 支持三种内置数据源

  1. EnvSource():从环境变量读取。在环境变量中查找字段名的大写形式(例如,HOST 对应 host)。
  2. FileSource(file_path: Path | str, use_env_var: bool = False):从 toml、json 或 yaml 文件读取。设置 use_env_var=True 允许通过环境变量指定文件路径。
  3. KeyvaultSource(keyvault_name: str, use_env_var: bool = False):从 Azure Key Vault 获取值。设置 use_env_var=True 允许通过环境变量指定 Key Vault 名称。

多数据源示例

from pydantic import BaseModel, Field
from essex_config import config
from essex_config.sources import EnvSource, FileSource, KeyVaultSource

@config(sources=[
    EnvSource(),
    FileSource("SETTINGS_PATH", use_env_name=True),
    KeyVaultSource("KEYVAULT_NAME", use_env_name=True),
    FileSource("pyproject.toml")
])
class CustomerDatabase(Config):
    """Configuration for connecting to the Customer Database"""
    host: str = Field(default="127.0.0.1", description="DB connection host")
    port: int = Field(description="DB connection port")
    password: str = Field(description="DB connection password")

字段按指定顺序从数据源中填充。

自定义数据源

通过实现一个 Source 对象并重写 _get_value()__contains__() 方法来自定义数据源。可选地重写 _format() 方法以提供前缀和键的自定义格式化。

自定义数据源示例

T = TypeVar("T")

class MockSource(Source):
    def __init__(self):
        self.data = {
            "hello": "world"
        }

    def _get_value(self, key: str, value_type: type[T]) -> T:
        return convert_to_type(self.data[key], value_type)

    def __contains__(self, key: str) -> bool:
        """Check if the key is present in the source."""
        return key in self.data

前缀

@config 装饰器支持为不同数据源中的值使用前缀

@config(prefix="customer_db")
class CustomerDatabase(BaseModel):
    """Configuration for connecting to the Customer Database"""
    host: str = Field(default="127.0.0.1", description="DB connection host")
    port: int = Field(description="DB connection port")
    password: str = Field(description="DB connection password")

使用前缀后,数据源会相应地查找值

  • EnvSource():使用大写蛇形命名(例如,CUSTOMER_DB_HOSTCUSTOMER_DB_PORTCUSTOMER_DB_PASSWORD)。
  • FileSource():更深入地查找文件结构(例如,customer_db.host)。
  • KeyvaultSource():使用点号连接前缀和键。

要为特定字段添加前缀,请使用 Annotated

@config(prefix="customer_db")
class CustomerDatabase(BaseModel):
    """Configuration for connecting to the Customer Database"""
    host: Annotated[str, Prefixed("some_prefix")] = Field(default="127.0.0.1", description="DB connection host")
    port: int = Field(description="DB connection port")
    password: str = Field(description="DB connection password")

在这种情况下,host 的前缀将是 customer_db.some_prefix

别名

使用 Annotated 添加特定数据源的别名

@config(prefix="db")
class CustomerDatabase(BaseModel):
    """Configuration for connecting to the Customer Database"""
    host: Annotated[str, Alias(EnvSource, ["customer_db_host"])] = Field(default="127.0.0.1", description="DB connection host")
    port: int = Field(description="DB connection port")
    password: str = Field(description="DB connection password")

当使用 EnvSource 时,essex-config 将从 db.customer_db_host 中填充 host

嵌套配置

嵌套配置对象

class Inner(BaseModel):
    inner_hello: str

@config()
class NestedConfiguration(BaseModel):
    hello: str
    nested: Inner

nested_config = NestedConfiguration.load_config()

load_config() 会填充每个字段,包括 nested_config.nested.inner_hello。默认前缀为 Inner 中的每个字段是 nested,这可以通过 Annotated[Inner, Prefixed("new_prefix")] 来更改。

生成文档

将配置类的文档生成为一个 markdown 文件或打印到终端

python -m essex_config.doc_gen

使用 --output 选项指定 markdown 文件。

示例 markdown 文件可参考 CONFIG_EXAMPLE.md

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源代码分发

essex_config-0.0.5.tar.gz (13.0 kB 查看哈希值)

上传时间 源代码

构建分发

essex_config-0.0.5-py3-none-any.whl (17.6 kB 查看哈希值)

上传时间 Python 3

支持者:

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面