dataquantum-yaml-reader 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dataquantum_yaml_reader/__init__.py +7 -0
- dataquantum_yaml_reader/reader_yaml.py +54 -0
- dataquantum_yaml_reader-0.3.1.dist-info/METADATA +274 -0
- dataquantum_yaml_reader-0.3.1.dist-info/RECORD +6 -0
- dataquantum_yaml_reader-0.3.1.dist-info/WHEEL +4 -0
- dataquantum_yaml_reader-0.3.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import yaml
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_reader_yaml(config_path: Path) -> dict[str, Any]:
|
|
8
|
+
"""
|
|
9
|
+
Loads all YAML configuration files present in a
|
|
10
|
+
specified directory.
|
|
11
|
+
|
|
12
|
+
Parameters
|
|
13
|
+
----------
|
|
14
|
+
config_path : Path
|
|
15
|
+
Path to the directory containing the configuration files.
|
|
16
|
+
|
|
17
|
+
Returns
|
|
18
|
+
-------
|
|
19
|
+
Dict[str, Any]
|
|
20
|
+
A dictionary containing all the loaded configurations.
|
|
21
|
+
The key corresponds to the name of the YAML file, and the
|
|
22
|
+
value corresponds to the file's content converted into
|
|
23
|
+
a Python structure.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
# Initialize the dictionary that will store all configurations
|
|
27
|
+
# loaded from the YAML files.
|
|
28
|
+
configs: dict[str, Any] = {}
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
# Checks if the configuration directory exists.
|
|
32
|
+
if not config_path.exists():
|
|
33
|
+
raise FileNotFoundError(f"Configuration directory not found: {config_path}")
|
|
34
|
+
|
|
35
|
+
# Checks if the configuration path exists.
|
|
36
|
+
if not config_path.is_dir():
|
|
37
|
+
raise NotADirectoryError(
|
|
38
|
+
f"The specified path is not a directory: {config_path}"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Iterates through all files with the .yaml extension
|
|
42
|
+
for file in config_path.glob("*.yaml"):
|
|
43
|
+
# Opens the YAML file in read mode, using
|
|
44
|
+
# UTF-8 encoding to ensure compatibility.
|
|
45
|
+
with open(file, "r", encoding="utf-8") as f:
|
|
46
|
+
# Loads the YAML content securely using
|
|
47
|
+
# yaml.safe_load, which prevents the execution of arbitrary code.
|
|
48
|
+
configs[file.stem] = yaml.safe_load(f)
|
|
49
|
+
|
|
50
|
+
# Returns the dictionary containing all loaded settings.
|
|
51
|
+
return configs
|
|
52
|
+
|
|
53
|
+
except yaml.YAMLError as error:
|
|
54
|
+
raise ValueError(f"YAML_ERROR: error processing YAML -> {error}") from error
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dataquantum-yaml-reader
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: A Python package for reading YAML configuration files.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: yaml,configuration,reader,dataquantum
|
|
8
|
+
Author: jcarlossc
|
|
9
|
+
Author-email: jcarlossc1977@gmail.com
|
|
10
|
+
Requires-Python: >=3.11,<4.0
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Dist: pyyaml (>=6.0.3,<7.0.0)
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# DataQuantum YAML Reader
|
|
19
|
+
|
|
20
|
+
[](https://www.python.org/)
|
|
21
|
+
[](LICENSE)
|
|
22
|
+
|
|
23
|
+
Biblioteca Python para leitura de arquivos de configuração YAML, desenvolvida para simplificar o carregamento e a organização de configurações em projetos Python.
|
|
24
|
+
|
|
25
|
+
O `DataQuantum YAML Reader` permite ler múltiplos arquivos `.yaml` de um diretório e reunir suas configurações em um dicionário Python, utilizando o nome de cada arquivo como chave.
|
|
26
|
+
|
|
27
|
+
Desenvolvido pela **DataQuantum**, marca dedicada a soluções de análise de dados, ciência de dados e engenharia de dados.
|
|
28
|
+
|
|
29
|
+
## Funcionalidades
|
|
30
|
+
|
|
31
|
+
- Leitura de múltiplos arquivos `.yaml` de um diretório.
|
|
32
|
+
- Carregamento seguro dos arquivos utilizando `yaml.safe_load`.
|
|
33
|
+
- Organização das configurações em um dicionário Python.
|
|
34
|
+
- Utilização do nome de cada arquivo como chave do dicionário.
|
|
35
|
+
- Suporte a estruturas YAML aninhadas.
|
|
36
|
+
- Integração com projetos Python e pipelines ETL.
|
|
37
|
+
|
|
38
|
+
## Requisitos
|
|
39
|
+
|
|
40
|
+
- Python 3.11 ou superior.
|
|
41
|
+
- PyYAML 6.0.3 ou superior, dentro do intervalo de versões declarado pelo pacote.
|
|
42
|
+
|
|
43
|
+
## Instalação
|
|
44
|
+
|
|
45
|
+
### Com pip
|
|
46
|
+
|
|
47
|
+
Instale a biblioteca diretamente do PyPI:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install dataquantum-yaml-reader
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Com Poetry
|
|
54
|
+
|
|
55
|
+
Adicione a biblioteca como dependência do projeto:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
poetry add dataquantum-yaml-reader
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Estrutura de diretórios
|
|
62
|
+
|
|
63
|
+
Crie o diretório `config` na raiz do projeto para armazenar os arquivos de configuração com extensão `.yaml`.
|
|
64
|
+
|
|
65
|
+
## Exemplo de utilização
|
|
66
|
+
|
|
67
|
+
Considere a seguinte estrutura de diretórios:
|
|
68
|
+
|
|
69
|
+
```text
|
|
70
|
+
projeto/
|
|
71
|
+
├── config/
|
|
72
|
+
│ └── logging.yaml
|
|
73
|
+
├── src/
|
|
74
|
+
│ └── main.py
|
|
75
|
+
└── pyproject.toml
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
O arquivo `logging.yaml` contém:
|
|
79
|
+
|
|
80
|
+
```yaml
|
|
81
|
+
logging_info:
|
|
82
|
+
level: "INFO"
|
|
83
|
+
format: "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
|
|
84
|
+
encoding: "utf-8"
|
|
85
|
+
|
|
86
|
+
logs:
|
|
87
|
+
file: "logs/app.log"
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Lendo os arquivos YAML
|
|
91
|
+
|
|
92
|
+
Importe a função `get_reader_yaml` e informe o caminho do diretório que contém os arquivos de configuração.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from pathlib import Path
|
|
96
|
+
|
|
97
|
+
from dataquantum_yaml_reader import get_reader_yaml
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# Localiza a raiz do projeto, um nível acima de src/.
|
|
101
|
+
project_root = Path(__file__).resolve().parent.parent
|
|
102
|
+
|
|
103
|
+
# Define o caminho absoluto para o diretório de configurações.
|
|
104
|
+
config_path = project_root / "config"
|
|
105
|
+
|
|
106
|
+
configs = get_reader_yaml(config_path)
|
|
107
|
+
|
|
108
|
+
print(configs)
|
|
109
|
+
```
|
|
110
|
+
### Como funciona?
|
|
111
|
+
- ```__file__```: caminho do arquivo main.py.
|
|
112
|
+
- ```.resolve()```: transforma o caminho em absoluto.
|
|
113
|
+
- ```.parent```: retorna o diretório src/.
|
|
114
|
+
- ```.parent.parent```: retorna a raiz do projeto.
|
|
115
|
+
- ```/ "config"```: acrescenta o diretório config/ ao caminho.
|
|
116
|
+
|
|
117
|
+
### Resultado esperado
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
{
|
|
121
|
+
"logging": {
|
|
122
|
+
"logging_info": {
|
|
123
|
+
"level": "INFO",
|
|
124
|
+
"format": "%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
|
125
|
+
"encoding": "utf-8",
|
|
126
|
+
},
|
|
127
|
+
"logs": {"file": "logs/app.log"},
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
O dicionário contém uma entrada para cada arquivo `.yaml` encontrado. A chave corresponde ao nome do arquivo sem a extensão, e o valor corresponde ao conteúdo carregado.
|
|
133
|
+
|
|
134
|
+
## Utilizando as configurações
|
|
135
|
+
|
|
136
|
+
Após carregar os arquivos, você pode acessar os valores por meio das chaves do dicionário.
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from pathlib import Path
|
|
140
|
+
|
|
141
|
+
from dataquantum_yaml_reader import get_reader_yaml
|
|
142
|
+
|
|
143
|
+
# Localiza a raiz do projeto, um nível acima de src/.
|
|
144
|
+
project_root = Path(__file__).resolve().parent.parent
|
|
145
|
+
|
|
146
|
+
# Define o caminho absoluto para o diretório de configurações.
|
|
147
|
+
config_path = project_root / "config"
|
|
148
|
+
|
|
149
|
+
configs = get_reader_yaml(config_path)
|
|
150
|
+
|
|
151
|
+
logging_config = configs["logging"]
|
|
152
|
+
|
|
153
|
+
level = logging_config["logging_info"]["level"]
|
|
154
|
+
log_format = logging_config["logging_info"]["format"]
|
|
155
|
+
encoding = logging_config["logging_info"]["encoding"]
|
|
156
|
+
log_file = logging_config["logs"]["file"]
|
|
157
|
+
|
|
158
|
+
print(level)
|
|
159
|
+
print(log_format)
|
|
160
|
+
print(encoding)
|
|
161
|
+
print(log_file)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Saída:
|
|
165
|
+
|
|
166
|
+
```text
|
|
167
|
+
INFO
|
|
168
|
+
%(asctime)s - %(levelname)s - %(name)s - %(message)s
|
|
169
|
+
utf-8
|
|
170
|
+
logs/app.log
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Quais erros podem ocorrer?
|
|
174
|
+
|
|
175
|
+
| Exceção | Situação |
|
|
176
|
+
|---|---|
|
|
177
|
+
| `FileNotFoundError` | O caminho informado não existe. |
|
|
178
|
+
| `NotADirectoryError` | O caminho existe, mas aponta para um arquivo, não para um diretório. |
|
|
179
|
+
| `ValueError` | Um arquivo YAML contém sintaxe inválida. |
|
|
180
|
+
| `OSError` | Ocorre um erro do sistema operacional ao acessar ou ler arquivos. |
|
|
181
|
+
|
|
182
|
+
**Arquivos YAML vazios:** não geram erro com `yaml.safe_load()`.
|
|
183
|
+
O valor correspondente no dicionário será `None`.
|
|
184
|
+
|
|
185
|
+
## Aplicações
|
|
186
|
+
|
|
187
|
+
A biblioteca pode ser utilizada em diferentes contextos:
|
|
188
|
+
|
|
189
|
+
- **Análise de dados:** centralização de configurações de projetos analíticos.
|
|
190
|
+
- **Ciência de dados:** carregamento de parâmetros e configurações de experimentos.
|
|
191
|
+
- **Engenharia de dados:** gerenciamento de configurações de pipelines ETL.
|
|
192
|
+
- **Automação:** leitura de configurações utilizadas em scripts Python.
|
|
193
|
+
- **Integração de sistemas:** organização de parâmetros de conexão e configurações de aplicações.
|
|
194
|
+
|
|
195
|
+
## Desenvolvimento
|
|
196
|
+
|
|
197
|
+
Este projeto utiliza Poetry para gerenciamento de dependências e do ambiente de desenvolvimento.
|
|
198
|
+
|
|
199
|
+
Clone o repositório:
|
|
200
|
+
|
|
201
|
+
```bash
|
|
202
|
+
git clone https://github.com/jcarlossc/dataquantum-yaml-reader.git
|
|
203
|
+
|
|
204
|
+
cd dataquantum-yaml-reader
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Instale as dependências:
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
poetry install
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Execute os testes:
|
|
214
|
+
|
|
215
|
+
```bash
|
|
216
|
+
poetry run task pytest
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Execute os testes com relatório de cobertura:
|
|
220
|
+
|
|
221
|
+
```bash
|
|
222
|
+
poetry run task covcmd
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Execute as verificações de qualidade:
|
|
226
|
+
|
|
227
|
+
```bash
|
|
228
|
+
poetry run task check
|
|
229
|
+
poetry run task lint
|
|
230
|
+
poetry run task mypy
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Execute a validação completa para o release:
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
poetry run task release-check
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## Testes e qualidade
|
|
240
|
+
|
|
241
|
+
O projeto utiliza ferramentas para garantir a qualidade, a manutenção e a confiabilidade do código:
|
|
242
|
+
|
|
243
|
+
- **pytest:** execução dos testes automatizados.
|
|
244
|
+
- **pytest-cov:** medição da cobertura dos testes.
|
|
245
|
+
- **Ruff:** análise estática e formatação do código.
|
|
246
|
+
- **mypy:** verificação estática de tipos.
|
|
247
|
+
- **pre-commit:** execução de verificações automatizadas antes dos commits.
|
|
248
|
+
- **GitHub Actions:** integração contínua e automação de tarefas.
|
|
249
|
+
- **Release Please:** gerenciamento automatizado de releases e changelog.
|
|
250
|
+
|
|
251
|
+
## Versionamento
|
|
252
|
+
|
|
253
|
+
O projeto segue o Versionamento Semântico (*Semantic Versioning*), utilizando o formato:
|
|
254
|
+
|
|
255
|
+
`MAJOR.MINOR.PATCH`
|
|
256
|
+
|
|
257
|
+
- **MAJOR:** alterações incompatíveis com versões anteriores.
|
|
258
|
+
- **MINOR:** novas funcionalidades compatíveis com versões anteriores.
|
|
259
|
+
- **PATCH:** correções compatíveis com a versão existente.
|
|
260
|
+
|
|
261
|
+
Consulte o arquivo `CHANGELOG.md` para acompanhar o histórico de alterações.
|
|
262
|
+
|
|
263
|
+
## Licença
|
|
264
|
+
|
|
265
|
+
Este projeto está licenciado sob a licença MIT. Consulte o arquivo `LICENSE` para obter mais informações.
|
|
266
|
+
|
|
267
|
+
## Autor e contato
|
|
268
|
+
|
|
269
|
+
**DataQuantum**
|
|
270
|
+
|
|
271
|
+
- GitHub: [jcarlossc](https://github.com/jcarlossc)
|
|
272
|
+
- Repositório: [dataquantum-yaml-reader](https://github.com/jcarlossc/dataquantum-yaml-reader)
|
|
273
|
+
- E-mail: jcarlossc1977@gmail.com
|
|
274
|
+
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
dataquantum_yaml_reader/__init__.py,sha256=JmFy7XcE9yTHMzaUxMgWSmiK85MnMwIWbXOnJJcYRZs,146
|
|
2
|
+
dataquantum_yaml_reader/reader_yaml.py,sha256=g_RkfIbyNKTRVfMbQAMHW6WLwaV_QlD-mRCPjZKmkyo,1818
|
|
3
|
+
dataquantum_yaml_reader-0.3.1.dist-info/METADATA,sha256=Gpzg0o3M2uYl1J1BjbuZ4PsqgvxP78FDz9zfE-GUPsQ,7633
|
|
4
|
+
dataquantum_yaml_reader-0.3.1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
5
|
+
dataquantum_yaml_reader-0.3.1.dist-info/licenses/LICENSE,sha256=XtVXtSY11uUnSjQnuVdYp3dHuCr3v1EWzvR9iBNp0qo,1072
|
|
6
|
+
dataquantum_yaml_reader-0.3.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Carlos da Costa
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|