Skip to main content

A lightweight configuration base class for small to medium-sized Python projects.

Project description

介绍

这是一个可为中小型 Python 项目提供配置管理的基类。

配置文件使用 YAML 格式,人类易读。

最简易的配置管理方案,就是单个文件里存放全部的配置,解析 YAML 后,直接用字典、列表去访问。但这样的缺点是没有代码补全,在配置有增删时也无法让程序静态分析,但更为不便的是没法复用一些相对固定的配置。

本库提出的方案,仅通过少量代码,再加上一点编程规范,解决了上述问题:

  • 手工将程序所需的配置一一作为属性添加到数据类上,这样实现代码补全,方便静态分析
  • 提供解析配置文件的类方法,该方法接收单个配置文件路径,并从中得到其他配置文件路径,最终将这些配置合而为一,实现复用

用法

继承基类创建项目的配置类,基类中提供了一些有用的类方法。

# config_handle.py
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Self

from briefconf import BriefConfig

# 请自行更改环境变量的名称
configfile = os.getenv("PROJECT_CONFIG_FILE", default="config.yaml")
merged_config = os.getenv("PROJECT_MERGED_CONFIG", default="")  # 如果要查看合并后的配置,就通过此环境变量传递路径


@dataclass(frozen=True, slots=True)
class Config(BriefConfig):
    """所有配置参数都作为属性,列举在下面。通过类方法初始化配置实例,将配置的获取和配置参数分开放置,程序结构更加清晰。"""
    is_production: bool

    @classmethod
    def load(cls, config_path: str) -> Self:
        configs = cls._load_config(config_path)
        if merged_config:
            Path(merged_config).write_text(BriefConfig._dump(configs))

        return cls(
            is_production=configs["is_production"]
        )


config = Config.load(os.path.abspath(configfile))

在其他文件中获得配置参数的值,直接引入实例即可: from config_handle import config


更具体的使用案例,可以查看 tests/config_handle.py

合并规则

  1. 配置文件中需要包含键值对 other_configs_path: [],里面放上其他配置文件路径。
  2. other_configs_path 中靠后的配置会覆盖或追加到靠前的配置,具体为:
    • 如果值是字符串、数字、布尔类型,会覆盖靠前的配置;
    • 如果值是列表类型,会追加到后面;
    • 如果值是字典类型,对于重复的字段,根据值的类型,由前面规则决定;新字段会添加进字典。
    • 如果值为 null ,无论值的类型是什么,都会设置为 None。
    • 如果键是新增的,或者之前键的值为 None,会使用新值替换 None。(借助后面两条规则,实现删除旧值功能,进而让靠后的配置可以重新赋值,避免引入靠前配置里不想要的值)
  3. 当前配置文件会覆盖 other_configs_path 中合并后的配置。
  4. 合并过程中,如果遇到已经处理过的配置文件,会直接忽略。

如下面的简单例子,config.yaml 里引入 pgm_config.yaml,根据字典规则,新字段会添加,因此最终解析后的对象里拥有 data_dir: config_and_data_filesis_production: false

# config.yaml
other_configs_path:
- pgm_config.yaml

is_production: false
# pgm_config.yaml
data_dir: config_and_data_files

如果要自定义这个键(other_configs_path)的名称,可以通过修改类成员实现

class CustomConfig(BriefConfig):
    _key4merge_files: ClassVar[str] = "include" # 自定义键名

    is_production: bool

    @classmethod
    def load(cls, config_path: str) -> Self:
        pass

优先从环境变量中加载值

提供了一个方便使用的类函数,传入合并后的配置字典,键的名称和缺省值,会优先返回环境变量里的值,其次是配置字典里的值,都没有的话,则返回缺省值。

值得注意的是,环境变量名称将会是传入的键的名称的全大写;如果设置了前缀(修改类成员 _env_var_prefix ),则环境变量名称是“前缀_键的名称”,全大写。

可以在创建 config 实例时,根据需要,对一些属性用这个方法:

    return cls(
        queue_name=cls.get_config_value(configs, "queue_name", ""),
    )

版本迭代

如果将来 BriefConfig 提供的类方法或行为与之前版本不兼容,会将旧版本保留在子模块中,这样升级后出现问题,只需要从子模块引入即可

from briefconf import BriefConfig

class Config(BriefConfig):
    ...

从子模块中引入旧的版本

from briefconf.v1 import BriefConfig

class Config(BriefConfig):
    ...

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

briefconf-0.1.5.tar.gz (8.1 kB view details)

Uploaded Source

Built Distribution

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

briefconf-0.1.5-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file briefconf-0.1.5.tar.gz.

File metadata

  • Download URL: briefconf-0.1.5.tar.gz
  • Upload date:
  • Size: 8.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.13

File hashes

Hashes for briefconf-0.1.5.tar.gz
Algorithm Hash digest
SHA256 d56fc0994c636610d9a29e8bf72c5014c3c138f3303d4f42fdfdbb562a523a49
MD5 85053406bfec99d928f2674708f24667
BLAKE2b-256 12b69a2228115bfd9de50c78712e0a4f4926a49093cedd9085e22c90baa9551f

See more details on using hashes here.

File details

Details for the file briefconf-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: briefconf-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 5.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.13

File hashes

Hashes for briefconf-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 fd91764785f468152c18fab829c9070bdb5f5d430226d5949f41acb1f6d2f2e9
MD5 731eb4a71245af419d9477424b7a0bd5
BLAKE2b-256 b630991dd6ac80e0816f5f813f80675a01a265fafae1261b3655e3b8920bebf1

See more details on using hashes here.

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