Configuration management with deferred binding and value templating
Project description
Toya
EN
A minimalistic library for flexible configuration reading.
Allows using the Jinja templating engine.
Values are evaluated lazily, after complete reading and merging of all configuration sources.
Project Integration
Module name: toya
Example integration with Rye:
rye add toya
Usage Example
test4.yaml:
c1: v1
c2: v2
c3:
c31: v31
c32: v32
c33: !t "{{ _.c1 }}/{{ _.c2 }}/{{ c31 }}/{{ c32 }}"
Environment:
APP__C2=e2
APP__C3__C32=e32
Code:
from pathlib import Path
from typing import Any, MutableMapping
from toya.config import load_and_eval_config
from toya.supplier.env_supplier import EnvSupplier
from toya.supplier.mapping_supplier import MappingSupplier
from toya.supplier.yaml_supplier import YamlSupplier
from toya.tpl import create_tpl_type
yaml_supplier = YamlSupplier(Path("test4.yaml"))
env_supplier = EnvSupplier()
tpl_type = create_tpl_type()
mapping_supplier = MappingSupplier({
"c3": {
"c32": tpl_type("{{ _.c1 }}@{{ c31 }}")
},
})
cfg: MutableMapping[str, Any] = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])
assert cfg["c3"]["c33"] == "v1/e2/v31/v1@v31"
Explanation
Configuration is read from the specified sources sequentially. A source specified later overwrites values from sources specified earlier.
Then the evaluation of values specified with the
!t tag occurs (the tag can be specified during initialization). Values are evaluated
sequentially, from top to bottom.
In templates, you can use all Jinja capabilities. Additionally, you can reference other variables.
- If a variable name is specified without prefixes, it is considered to be a
variable from the same group. For example,
c33referencesc31without a prefix. - If you need to reference an arbitrary variable, you need to specify the full
path to it, using the
_prefix as the root element. For example,c33referencesc1by specifying the full path_.c1. The variablec33itself will have the full path_.c3.c33.
The result is returned as a dictionary. It can be used, for example, with Pydantic:
from pydantic import BaseModel
class Config(BaseModel):
c1: str
c2: str
class C3(BaseModel):
c33: str
c3: C3
raw_cfg = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])
cfg = Config.model_validate(raw_cfg)
RU
Минималистичная библиотека для гибкого чтения конфигурации.
Позволяется использовать шаблонизатор Jinja.
Значения вычисляются отложено, после полного прочтения и слияния всех источников конфигурации.
Подключение в проект
Имя модуля: toya
Пример подключения в Rye:
rye add toya
Пример использования
test4.yaml:
c1: v1
c2: v2
c3:
c31: v31
c32: v32
c33: !t "{{ _.c1 }}/{{ _.c2 }}/{{ c31 }}/{{ c32 }}"
Environment:
APP__C2=e2
APP__C3__C32=e32
Code:
from pathlib import Path
from typing import Any, MutableMapping
from toya.config import load_and_eval_config
from toya.supplier.env_supplier import EnvSupplier
from toya.supplier.mapping_supplier import MappingSupplier
from toya.supplier.yaml_supplier import YamlSupplier
from toya.tpl import create_tpl_type
yaml_supplier = YamlSupplier(Path("test4.yaml"))
env_supplier = EnvSupplier()
tpl_type = create_tpl_type()
mapping_supplier = MappingSupplier({
"c3": {
"c32": tpl_type("{{ _.c1 }}@{{ c31 }}")
},
})
cfg: MutableMapping[str, Any] = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])
assert cfg["c3"]["c33"] == "v1/e2/v31/v1@v31"
Пояснение
Конфигурация читается из указанных источников последовательно. Источник, указанный позже, перезаписывает значения источников, указанных раньше.
Далее происходит вычисление значений, указанных с тегом
!t (тег можно указать при инициализации). Значения вычисляются
последовательно, сверху вниз.
В шаблонах можно использовать все возможности Jinja. Кроме того можно ссылаться на другие переменные.
- Если имя переменной указано без префиксов, то считается, что это
переменная из той же группы. Например,
c33обращается кс31без префикса. - Если нужно обратиться к произвольной переменной, то нужно указать полный
путь к ней, используя префикс
_как корневой элемент. Например,c33обращается кc1с указанием полного пути_.c1. Сама переменнаяс33будет иметь полный путь_.c3.c33.
Результат возвращается в виде словаря. Его можно использовать, например, с Pydantic:
from pydantic import BaseModel
class Config(BaseModel):
c1: str
c2: str
class C3(BaseModel):
c33: str
c3: C3
raw_cfg = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])
cfg = Config.model_validate(raw_cfg)
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 toya-1.0.2.tar.gz.
File metadata
- Download URL: toya-1.0.2.tar.gz
- Upload date:
- Size: 8.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d92a81f5867d0e54b96f5d882fa9ad8064c7877e28c709d5a631a58654643745
|
|
| MD5 |
8685c6aa59200d3881160c2c9d69a1cf
|
|
| BLAKE2b-256 |
0af96fbc0d14f9f08135195ff743b057236e2b7cd5fcdd69c49b21a9366aa269
|
Provenance
The following attestation bundles were made for toya-1.0.2.tar.gz:
Publisher:
python-publish.yml on cs0ip/toya
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
toya-1.0.2.tar.gz -
Subject digest:
d92a81f5867d0e54b96f5d882fa9ad8064c7877e28c709d5a631a58654643745 - Sigstore transparency entry: 246020051
- Sigstore integration time:
-
Permalink:
cs0ip/toya@be57ddef7da96676e0223f365ef3469c8aff11c4 -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/cs0ip
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@be57ddef7da96676e0223f365ef3469c8aff11c4 -
Trigger Event:
release
-
Statement type:
File details
Details for the file toya-1.0.2-py3-none-any.whl.
File metadata
- Download URL: toya-1.0.2-py3-none-any.whl
- Upload date:
- Size: 7.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
592143704efe0b6c83cec0407dd1a849367072406213bf2bc781736c0ffd81c9
|
|
| MD5 |
7a48e681494134117a11a4a378af95ca
|
|
| BLAKE2b-256 |
6f760ff3dd8a540efbd07f830bdbce4385bca63a58b0911cbd3fdd943ff57156
|
Provenance
The following attestation bundles were made for toya-1.0.2-py3-none-any.whl:
Publisher:
python-publish.yml on cs0ip/toya
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
toya-1.0.2-py3-none-any.whl -
Subject digest:
592143704efe0b6c83cec0407dd1a849367072406213bf2bc781736c0ffd81c9 - Sigstore transparency entry: 246020052
- Sigstore integration time:
-
Permalink:
cs0ip/toya@be57ddef7da96676e0223f365ef3469c8aff11c4 -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/cs0ip
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@be57ddef7da96676e0223f365ef3469c8aff11c4 -
Trigger Event:
release
-
Statement type: