四叶的配置管理工具 — 基于 Pydantic 的配置加载器,上下文管理器自动读写
Project description
FovesConfig
基于 Pydantic 的配置管理工具,上下文管理器自动读写 JSON 配置文件。
可使用 pip 安装或下载源码使用:
pip install FovesConfig
项目主页: https://github.com/Foves7017/FovesLib
ConfigLoader
泛型配置加载器。把你的配置定义成一个 Pydantic 模型,然后用 ConfigLoader 包裹它——进入上下文自动读取 JSON,退出时自动写回,省去所有手工序列化的麻烦。
基本用法
from pydantic import BaseModel
from FovesConfig import ConfigLoader
class AppConfig(BaseModel):
host: str = "localhost"
port: int = 8080
debug: bool = False
with ConfigLoader("config.json", AppConfig) as cfg:
print(cfg.host) # 首次运行会使用默认值
cfg.port = 9090 # 修改配置
# 退出上下文时自动写入 config.json
参数
path: str | Path — 配置文件路径。文件存在则读取,不存在则使用模型默认值。
model: Type[T] — 一个 Pydantic BaseModel 子类,定义了配置的结构和默认值。
只读
你可以使用如下的方法只读取磁盘上的配置,在此例中,就算修改 cfg 的值也不会同步到磁盘中。
loader = ConfigLoader("config.json", AppConfig)
cfg = loader.readonly()
print(cfg.host)
读写行为
- 读取:进入上下文管理器时,若文件存在则
model_validate_json反序列化,否则用model_cls()构造默认实例。 - 写入:退出上下文管理器时自动创建父目录,以
indent=2、ensure_ascii=False写出 JSON。
其他
如果你发现自己需要手动调用 save() 或 exit(),请先考虑是否应该使用上下文管理器。大多数修改配置的场景都更适合:
with ConfigLoader(...) as config:
...
而不是手动管理配置对象的生命周期。
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fovesconfig-0.1.1.tar.gz.
File metadata
- Download URL: fovesconfig-0.1.1.tar.gz
- Upload date:
- Size: 5.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0de8a4be663f1a21f80b23cb1225ffb9bacb9ce1835882456d3c0d1696b0a387
|
|
| MD5 |
503218623c3d4681aab65ce5683fc933
|
|
| BLAKE2b-256 |
152f85b9302122fc1fa16d7da7eac8364d45b8e8861994e185522ee310f4ba71
|
File details
Details for the file fovesconfig-0.1.1-py3-none-any.whl.
File metadata
- Download URL: fovesconfig-0.1.1-py3-none-any.whl
- Upload date:
- Size: 4.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8fde1d446a862bdd6871284a8ef33a28178651fe2f30669a474ec13149cca84c
|
|
| MD5 |
9828f1ab1fe91c77d7df3ccbd7a2791a
|
|
| BLAKE2b-256 |
7b938e025738caf2600472dcf55fa2940f247055207f9d8ef9cfd30b41ca90e4
|