cloudru-qa-pydantic-extensions 1.0.0__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.
- cloudru_qa_pydantic_extensions-1.0.0.dist-info/METADATA +372 -0
- cloudru_qa_pydantic_extensions-1.0.0.dist-info/RECORD +14 -0
- cloudru_qa_pydantic_extensions-1.0.0.dist-info/WHEEL +4 -0
- cloudru_qa_pydantic_extensions-1.0.0.dist-info/licenses/LICENSE +202 -0
- pydantic_extensions/__init__.py +3 -0
- pydantic_extensions/fields/__init__.py +3 -0
- pydantic_extensions/fields/converters.py +22 -0
- pydantic_extensions/py.typed +1 -0
- pydantic_extensions/settings/__init__.py +11 -0
- pydantic_extensions/settings/sources/__init__.py +13 -0
- pydantic_extensions/settings/sources/base_source_type.py +337 -0
- pydantic_extensions/settings/sources/json.py +63 -0
- pydantic_extensions/settings/sources/toml.py +47 -0
- pydantic_extensions/settings/sources/yaml.py +72 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cloudru-qa-pydantic-extensions
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Расширения для Pydantic
|
|
5
|
+
Project-URL: Repository, https://github.com/cloud-ru-tech/qa-libraries
|
|
6
|
+
Project-URL: Issues, https://github.com/cloud-ru-tech/qa-libraries/issues
|
|
7
|
+
Author-email: Алексей Кирютин <ayukiryutin@cloud.ru>
|
|
8
|
+
Maintainer-email: Алексей Гапонов <avgaponov@cloud.ru>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Framework :: Pydantic :: 2
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.13
|
|
20
|
+
Requires-Dist: pydantic-settings<3,>=2.9.1
|
|
21
|
+
Requires-Dist: pydantic<3,>=2.11.5
|
|
22
|
+
Requires-Dist: pyhumps<4,>=3.8.0
|
|
23
|
+
Provides-Extra: toml
|
|
24
|
+
Requires-Dist: pydantic-settings[toml]<3,>=2.16.2; extra == 'toml'
|
|
25
|
+
Provides-Extra: yaml
|
|
26
|
+
Requires-Dist: pydantic-settings[yaml]<3,>=2.9.1; extra == 'yaml'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# Pydantic extensions
|
|
30
|
+
|
|
31
|
+
[](https://pypi.org/project/cloudru-qa-pydantic-extensions/)
|
|
32
|
+
[](https://pypi.org/project/cloudru-qa-pydantic-extensions/)
|
|
33
|
+
[](https://github.com/cloud-ru-tech/qa-libraries/blob/master/LICENSE)
|
|
34
|
+
|
|
35
|
+
English | [Русский](README.ru.md)
|
|
36
|
+
|
|
37
|
+
Extensions for [`pydantic`](https://docs.pydantic.dev/latest/).
|
|
38
|
+
|
|
39
|
+
- [Pydantic extensions](#pydantic-extensions)
|
|
40
|
+
- [Installation](#installation)
|
|
41
|
+
- [Skills for AI agents](#skills-for-ai-agents)
|
|
42
|
+
- [Usage](#usage)
|
|
43
|
+
- [The `fields` module](#the-fields-module)
|
|
44
|
+
- [Serialization and deserialization](#serialization-and-deserialization)
|
|
45
|
+
- [The `settings` module](#the-settings-module)
|
|
46
|
+
- [File key validation](#file-key-validation)
|
|
47
|
+
- [YAML settings](#yaml-settings)
|
|
48
|
+
- [JSON settings](#json-settings)
|
|
49
|
+
- [TOML settings](#toml-settings)
|
|
50
|
+
- [Encoding support](#encoding-support)
|
|
51
|
+
- [Loading multiple files](#loading-multiple-files)
|
|
52
|
+
- [Development](#development)
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
Requires Python 3.13 or later.
|
|
57
|
+
|
|
58
|
+
```shell
|
|
59
|
+
pip install cloudru-qa-pydantic-extensions
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Import the library as the module `pydantic_extensions`.
|
|
63
|
+
|
|
64
|
+
## Skills for AI agents
|
|
65
|
+
|
|
66
|
+
This library does not have its own skill yet. If your project uses other
|
|
67
|
+
libraries from this suite with [skills for AI agents](https://github.com/cloud-ru-tech/qa-libraries#skills-for-ai-agents),
|
|
68
|
+
select and enable them from your project root (requires [`uv`](https://docs.astral.sh/uv/)):
|
|
69
|
+
|
|
70
|
+
```shell
|
|
71
|
+
uvx library-skills
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
For Claude Code, add `--claude`.
|
|
75
|
+
|
|
76
|
+
## Usage
|
|
77
|
+
|
|
78
|
+
### The `fields` module
|
|
79
|
+
|
|
80
|
+
This module extends fields in pydantic models.
|
|
81
|
+
|
|
82
|
+
#### Serialization and deserialization
|
|
83
|
+
|
|
84
|
+
`CamelCaseBaseModel` and `PascalCaseBaseModel` convert field names to [`camelCase`](https://en.wikipedia.org/wiki/Camel_case) and `PascalCase`, respectively, when converting pydantic models to and from JSON.
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from pydantic_extensions.fields import CamelCaseBaseModel
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class User(CamelCaseBaseModel):
|
|
92
|
+
username: str
|
|
93
|
+
last_name: str
|
|
94
|
+
is_active: bool
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# Serialization
|
|
98
|
+
user = User(username="John", last_name="Smith", is_active=True)
|
|
99
|
+
assert user.model_dump_json() == '{"username":"John","lastName":"Smith","isActive":true}'
|
|
100
|
+
|
|
101
|
+
# Deserialization
|
|
102
|
+
json_content = {"username": "Aleksey", "lastName": "Petrov", "isActive": false}
|
|
103
|
+
user2 = User.model_validate(json_content)
|
|
104
|
+
assert user2.last_name == "Petrov"
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### The `settings` module
|
|
108
|
+
|
|
109
|
+
This module extends [`pydantic-settings`](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
|
|
110
|
+
|
|
111
|
+
#### Features
|
|
112
|
+
|
|
113
|
+
`JsonBaseSettings`, `TomlBaseSettings`, and `YamlBaseSettings` share these rules:
|
|
114
|
+
|
|
115
|
+
- Custom source order: `env -> dotenv -> secrets -> file -> init`.
|
|
116
|
+
- Support for a single file or a list of files.
|
|
117
|
+
- All specified files must exist (`FileNotFoundError`).
|
|
118
|
+
- Unknown file keys are rejected (`ValueError`).
|
|
119
|
+
- All required model keys must be present in the file or another source (env / dotenv / secrets / init) (`ValueError`).
|
|
120
|
+
- JSON/YAML files must have a `dict` root (`TypeError`).
|
|
121
|
+
|
|
122
|
+
#### File key validation
|
|
123
|
+
|
|
124
|
+
`JsonBaseSettings`, `TomlBaseSettings`, and `YamlBaseSettings` support two `SettingsConfigDict` flags:
|
|
125
|
+
|
|
126
|
+
- `validate_unknown_keys` (default `True`): reject unknown file keys.
|
|
127
|
+
- `validate_required_keys` (default `True`): check required model keys when reading the source. A key is missing only if it is absent from both the file and all other sources (env / dotenv / secrets / init). Required fields can therefore be set through environment variables without duplicating them in the file.
|
|
128
|
+
|
|
129
|
+
Strict mode (default):
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from pydantic import Field
|
|
133
|
+
from pydantic_settings import SettingsConfigDict
|
|
134
|
+
from pydantic_extensions.settings import JsonBaseSettings
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class MySettings(JsonBaseSettings):
|
|
138
|
+
app_name: str
|
|
139
|
+
debug: bool = Field(default=False)
|
|
140
|
+
|
|
141
|
+
model_config = SettingsConfigDict(
|
|
142
|
+
json_file="config.json",
|
|
143
|
+
validate_unknown_keys=True,
|
|
144
|
+
validate_required_keys=True,
|
|
145
|
+
)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Ignore unknown keys:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from pydantic import Field
|
|
152
|
+
from pydantic_settings import SettingsConfigDict
|
|
153
|
+
from pydantic_extensions.settings import TomlBaseSettings
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class MySettings(TomlBaseSettings):
|
|
157
|
+
app_name: str = Field(default="")
|
|
158
|
+
|
|
159
|
+
model_config = SettingsConfigDict(
|
|
160
|
+
toml_file="config.toml",
|
|
161
|
+
validate_unknown_keys=False,
|
|
162
|
+
)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
With `validate_unknown_keys=False`, extra keys are filtered out of the file source automatically, so `extra="ignore"` is not needed.
|
|
166
|
+
|
|
167
|
+
Disable early validation of required keys:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
from pydantic_settings import SettingsConfigDict
|
|
171
|
+
from pydantic_extensions.settings import YamlBaseSettings
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class MySettings(YamlBaseSettings):
|
|
175
|
+
app_name: str
|
|
176
|
+
debug: bool = False
|
|
177
|
+
|
|
178
|
+
model_config = SettingsConfigDict(
|
|
179
|
+
yaml_file="config.yaml",
|
|
180
|
+
validate_required_keys=False,
|
|
181
|
+
)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
In this mode, the library does not check required keys when reading the file. Final pydantic model validation still runs.
|
|
185
|
+
|
|
186
|
+
If a field has a default value, a missing file key does not cause an error; the `default` is used:
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
from pydantic import Field
|
|
190
|
+
from pydantic_settings import SettingsConfigDict
|
|
191
|
+
from pydantic_extensions.settings import YamlBaseSettings
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class MySettings(YamlBaseSettings):
|
|
195
|
+
app_name: str = Field(default="my-app")
|
|
196
|
+
debug: bool = Field(default=False)
|
|
197
|
+
|
|
198
|
+
model_config = SettingsConfigDict(
|
|
199
|
+
yaml_file="config.yaml",
|
|
200
|
+
validate_required_keys=False,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
settings = MySettings()
|
|
205
|
+
# If config.yaml has no app_name, settings.app_name == "my-app"
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
If no `default` is set, pydantic raises `ValidationError`:
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from pydantic_settings import SettingsConfigDict
|
|
212
|
+
from pydantic_extensions.settings import YamlBaseSettings
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class MySettings(YamlBaseSettings):
|
|
216
|
+
app_name: str
|
|
217
|
+
|
|
218
|
+
model_config = SettingsConfigDict(
|
|
219
|
+
yaml_file="config.yaml",
|
|
220
|
+
validate_required_keys=False,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
MySettings() # ValidationError if app_name is missing from config.yaml
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
#### YAML settings
|
|
228
|
+
|
|
229
|
+
Use `YamlBaseSettings` to load settings from one or more YAML files:
|
|
230
|
+
|
|
231
|
+
```python
|
|
232
|
+
from pydantic import Field
|
|
233
|
+
from pydantic_settings import SettingsConfigDict
|
|
234
|
+
from pydantic_extensions.settings import YamlBaseSettings
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class MySettings(YamlBaseSettings):
|
|
238
|
+
app_name: str = Field(default="")
|
|
239
|
+
debug: bool = Field(default=False)
|
|
240
|
+
port: int = Field(default=0)
|
|
241
|
+
|
|
242
|
+
model_config = SettingsConfigDict(yaml_file="config.yaml")
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Install the extra dependency for YAML support:
|
|
246
|
+
```shell
|
|
247
|
+
pip install "cloudru-qa-pydantic-extensions[yaml]"
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
#### JSON settings
|
|
251
|
+
|
|
252
|
+
Use `JsonBaseSettings` to load settings from one or more JSON files:
|
|
253
|
+
|
|
254
|
+
```python
|
|
255
|
+
from pydantic import Field
|
|
256
|
+
from pydantic_settings import SettingsConfigDict
|
|
257
|
+
from pydantic_extensions.settings import JsonBaseSettings
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class MySettings(JsonBaseSettings):
|
|
261
|
+
app_name: str = Field(default="")
|
|
262
|
+
debug: bool = Field(default=False)
|
|
263
|
+
port: int = Field(default=0)
|
|
264
|
+
|
|
265
|
+
model_config = SettingsConfigDict(json_file="config.json")
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
#### TOML settings
|
|
269
|
+
|
|
270
|
+
Use `TomlBaseSettings` to load settings from one or more TOML files:
|
|
271
|
+
|
|
272
|
+
```python
|
|
273
|
+
from pydantic import Field
|
|
274
|
+
from pydantic_settings import SettingsConfigDict
|
|
275
|
+
from pydantic_extensions.settings import TomlBaseSettings
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class MySettings(TomlBaseSettings):
|
|
279
|
+
app_name: str = Field(default="")
|
|
280
|
+
debug: bool = Field(default=False)
|
|
281
|
+
port: int = Field(default=0)
|
|
282
|
+
|
|
283
|
+
model_config = SettingsConfigDict(toml_file="config.toml")
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Install the extra dependency for TOML support:
|
|
287
|
+
```shell
|
|
288
|
+
pip install "cloudru-qa-pydantic-extensions[toml]"
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
#### Encoding support
|
|
292
|
+
|
|
293
|
+
For YAML and JSON settings, set the file encoding with `*_file_encoding`:
|
|
294
|
+
|
|
295
|
+
```python
|
|
296
|
+
model_config = SettingsConfigDict(yaml_file="config.yaml", yaml_file_encoding="windows-1251")
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
#### Loading multiple files
|
|
300
|
+
|
|
301
|
+
All settings classes support loading multiple files. This is useful when each environment has its own file alongside a shared settings file. For example, with YAML:
|
|
302
|
+
|
|
303
|
+
```python
|
|
304
|
+
import os
|
|
305
|
+
|
|
306
|
+
from pydantic import Field
|
|
307
|
+
from pydantic_settings import SettingsConfigDict
|
|
308
|
+
from pydantic_extensions.settings import YamlBaseSettings
|
|
309
|
+
|
|
310
|
+
ENV = os.getenv("ENV")
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class MySettings(YamlBaseSettings):
|
|
314
|
+
app_name: str = Field(default="")
|
|
315
|
+
debug: bool = Field(default=False)
|
|
316
|
+
port: int = Field(default=0)
|
|
317
|
+
|
|
318
|
+
model_config = SettingsConfigDict(
|
|
319
|
+
yaml_file=[
|
|
320
|
+
"config.common.yaml",
|
|
321
|
+
f"config.{ENV}.yaml",
|
|
322
|
+
],
|
|
323
|
+
)
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
If a variable occurs in both files, its value comes from the last file, `config.{ENV}.yaml` in this example.
|
|
327
|
+
|
|
328
|
+
YAML, TOML, and JSON configuration files can also be combined with `.env` files:
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
from pydantic import Field
|
|
332
|
+
from pydantic_settings import SettingsConfigDict
|
|
333
|
+
from pydantic_extensions.settings import YamlBaseSettings
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
class MySettings(YamlBaseSettings):
|
|
337
|
+
app_name: str = Field(default="")
|
|
338
|
+
debug: bool = Field(default=False)
|
|
339
|
+
port: int = Field(default=0)
|
|
340
|
+
|
|
341
|
+
# Read configuration from both env and YAML files.
|
|
342
|
+
# Source priority: env -> dotenv -> secrets -> file -> init.
|
|
343
|
+
model_config = SettingsConfigDict(
|
|
344
|
+
env_file=".env",
|
|
345
|
+
yaml_file=f"config.yaml",
|
|
346
|
+
)
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
## Development
|
|
350
|
+
|
|
351
|
+
This library is developed in the [qa-libraries](https://github.com/cloud-ru-tech/qa-libraries) monorepo
|
|
352
|
+
alongside the other `cloudru-qa-*` libraries. You need [`uv`](https://docs.astral.sh/uv/), GNU Make
|
|
353
|
+
and [`checkmake`](https://github.com/checkmake/checkmake);
|
|
354
|
+
run the commands from the repository root:
|
|
355
|
+
|
|
356
|
+
```shell
|
|
357
|
+
make sync # dependencies and extras for all libraries from uv.lock
|
|
358
|
+
make test-pydantic-extensions # tests for this library
|
|
359
|
+
make typecheck-pydantic-extensions # mypy for this library
|
|
360
|
+
make check # formatting, Ruff, mypy, and tests for the whole suite
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
⚠️ Keep the library lightweight and general purpose. Add dependencies only
|
|
364
|
+
when they are needed by all library users.
|
|
365
|
+
Make heavy dependencies optional (see
|
|
366
|
+
[the uv documentation](https://docs.astral.sh/uv/concepts/projects/dependencies/#optional-dependencies)).
|
|
367
|
+
|
|
368
|
+
Tests run on Python 3.13 and 3.14. Each version uses a separate environment:
|
|
369
|
+
`make sync test-pydantic-extensions PYTHON_VERSION=3.14`.
|
|
370
|
+
|
|
371
|
+
Create a release with the Git tag `pydantic-extensions/v<version>`. The tag version must match
|
|
372
|
+
the version in `packages/pydantic-extensions/pyproject.toml`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
pydantic_extensions/__init__.py,sha256=m0bbwB5b6AqfmHWsQciKBqsChW_gffgyzlQ6GWPnRsY,83
|
|
2
|
+
pydantic_extensions/py.typed,sha256=Jdt0ghgJyb7pQtIRSdUgjDmriFK1kVZPJHUaOLGjWmI,78
|
|
3
|
+
pydantic_extensions/fields/__init__.py,sha256=mGtve4sZUYMimOpHEvmSToTrPhqHFiDTpEodYIvseyQ,121
|
|
4
|
+
pydantic_extensions/fields/converters.py,sha256=2rrCNIYIVx_DGbQPk60EOU0huHgls_LNHOfSk693B3g,540
|
|
5
|
+
pydantic_extensions/settings/__init__.py,sha256=FYtTcBUfSvBZfjKluPQggNo2kMcuTlxNNc9TwTSUfQs,307
|
|
6
|
+
pydantic_extensions/settings/sources/__init__.py,sha256=WX58k3US3noZw_75BB-Jtbz0n5z-lpw9y-EItBQjA7U,349
|
|
7
|
+
pydantic_extensions/settings/sources/base_source_type.py,sha256=r2feYI2o5-62hj4HG-chEPDXQwBEIUfMz-Qa4r4R3eU,12811
|
|
8
|
+
pydantic_extensions/settings/sources/json.py,sha256=AdhTNoBUrt0bBrYO__P5ugd_eHLaujGR7aRuOartfdI,2267
|
|
9
|
+
pydantic_extensions/settings/sources/toml.py,sha256=gp7U5HTzjbZTRDRPBrW8l5GHHU5m6DbLSyGemOrzaHk,1633
|
|
10
|
+
pydantic_extensions/settings/sources/yaml.py,sha256=P-hDgTIOxZZPAlm4jIxb9r0KHShH0hEFWK2kTrVtdPU,2686
|
|
11
|
+
cloudru_qa_pydantic_extensions-1.0.0.dist-info/METADATA,sha256=02x-8a4GVFhmIQ4ZaBe3JMBKx53l46o6VMmmNLnHUa4,11689
|
|
12
|
+
cloudru_qa_pydantic_extensions-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
cloudru_qa_pydantic_extensions-1.0.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
14
|
+
cloudru_qa_pydantic_extensions-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from humps import camelize, pascalize
|
|
2
|
+
from pydantic import BaseModel, ConfigDict
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class CamelCaseBaseModel(BaseModel):
|
|
6
|
+
"""Model that serializes fields in camelCase."""
|
|
7
|
+
|
|
8
|
+
model_config = ConfigDict(
|
|
9
|
+
alias_generator=camelize,
|
|
10
|
+
populate_by_name=True,
|
|
11
|
+
serialize_by_alias=True,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PascalCaseBaseModel(BaseModel):
|
|
16
|
+
"""Model that serializes fields in PascalCase."""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(
|
|
19
|
+
alias_generator=pascalize,
|
|
20
|
+
populate_by_name=True,
|
|
21
|
+
serialize_by_alias=True,
|
|
22
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Marker file indicating that the package supports type checking under PEP 561.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from .sources.base_source_type import FileSettingsConfigDict
|
|
2
|
+
from .sources.json import JsonBaseSettings
|
|
3
|
+
from .sources.toml import TomlBaseSettings
|
|
4
|
+
from .sources.yaml import YamlBaseSettings
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"FileSettingsConfigDict",
|
|
8
|
+
"JsonBaseSettings",
|
|
9
|
+
"TomlBaseSettings",
|
|
10
|
+
"YamlBaseSettings",
|
|
11
|
+
]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Base settings classes by configuration file type (json / yaml / toml)."""
|
|
2
|
+
|
|
3
|
+
from .base_source_type import FileTypeBaseSettings
|
|
4
|
+
from .json import JsonBaseSettings
|
|
5
|
+
from .toml import TomlBaseSettings
|
|
6
|
+
from .yaml import YamlBaseSettings
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"FileTypeBaseSettings",
|
|
10
|
+
"JsonBaseSettings",
|
|
11
|
+
"TomlBaseSettings",
|
|
12
|
+
"YamlBaseSettings",
|
|
13
|
+
]
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Base pydantic-settings class that loads values from a file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import ClassVar, Protocol, cast
|
|
9
|
+
|
|
10
|
+
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
|
|
11
|
+
from pydantic_settings.sources.utils import _get_alias_names
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FileSettingsConfigDict(SettingsConfigDict, total=False):
|
|
15
|
+
"""File source settings with additional key validation."""
|
|
16
|
+
|
|
17
|
+
validate_required_keys: bool
|
|
18
|
+
validate_unknown_keys: bool
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UnknownKeysFilteringMixin:
|
|
22
|
+
"""Mixin for optional filtering of unknown keys from source data."""
|
|
23
|
+
|
|
24
|
+
drop_unknown_keys: bool = False
|
|
25
|
+
allowed_keys_filter: set[str] | None = None
|
|
26
|
+
|
|
27
|
+
def set_unknown_keys_filter(self, allowed_keys: set[str]) -> None:
|
|
28
|
+
"""Limit the source to known model keys.
|
|
29
|
+
|
|
30
|
+
:param allowed_keys: keys allowed for loading.
|
|
31
|
+
"""
|
|
32
|
+
self.drop_unknown_keys = True
|
|
33
|
+
self.allowed_keys_filter = allowed_keys
|
|
34
|
+
|
|
35
|
+
def apply_unknown_keys_filter(self, data: dict[str, object]) -> dict[str, object]:
|
|
36
|
+
"""Remove unknown keys if filtering is enabled.
|
|
37
|
+
|
|
38
|
+
:param data: file source values.
|
|
39
|
+
:return: values allowed by the model.
|
|
40
|
+
"""
|
|
41
|
+
if self.drop_unknown_keys and self.allowed_keys_filter is not None:
|
|
42
|
+
return {key: value for key, value in data.items() if key in self.allowed_keys_filter}
|
|
43
|
+
return data
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SupportsUnknownKeysFiltering(Protocol):
|
|
47
|
+
"""Source capable of dropping unknown keys."""
|
|
48
|
+
|
|
49
|
+
def set_unknown_keys_filter(self, allowed_keys: set[str]) -> None:
|
|
50
|
+
"""Set the allowed keys.
|
|
51
|
+
|
|
52
|
+
:param allowed_keys: model field keys.
|
|
53
|
+
"""
|
|
54
|
+
...
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class FileTypeBaseSettings(BaseSettings, ABC):
|
|
58
|
+
"""Base file settings class with custom source priority.
|
|
59
|
+
|
|
60
|
+
The class uses built-in `pydantic-settings` file sources but adds
|
|
61
|
+
project-specific validation rules and a custom source order:
|
|
62
|
+
``env -> dotenv -> secrets -> file -> init``.
|
|
63
|
+
|
|
64
|
+
Read the file path from ``settings_cls.model_config`` using ``_paths_config_key``
|
|
65
|
+
(for example, ``json_file``).
|
|
66
|
+
|
|
67
|
+
Key features:
|
|
68
|
+
1. Check that the configuration path is set in ``model_config``.
|
|
69
|
+
2. Support one path or a list of paths and expand ``~``.
|
|
70
|
+
3. Raise ``FileNotFoundError`` if any file is missing.
|
|
71
|
+
4. Check the file for unknown keys (extra keys relative to the model).
|
|
72
|
+
5. Check the file for missing required model keys.
|
|
73
|
+
Both checks can be disabled through ``model_config``.
|
|
74
|
+
6. Respect field aliases and ``populate_by_name`` / ``validate_by_name`` modes.
|
|
75
|
+
|
|
76
|
+
Attributes:
|
|
77
|
+
_paths_config_key: ``model_config`` key containing a file path or list of paths.
|
|
78
|
+
_encoding_config_key: ``model_config`` key containing the encoding, or ``None``.
|
|
79
|
+
_missing_paths_error: Error text if no file path is set.
|
|
80
|
+
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
_paths_config_key: ClassVar[str]
|
|
84
|
+
_encoding_config_key: ClassVar[str | None]
|
|
85
|
+
_missing_paths_error: ClassVar[str]
|
|
86
|
+
_validate_required_keys_config_key: ClassVar[str] = "validate_required_keys"
|
|
87
|
+
_validate_unknown_keys_config_key: ClassVar[str] = "validate_unknown_keys"
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
@abstractmethod
|
|
91
|
+
def _build_file_source(
|
|
92
|
+
cls,
|
|
93
|
+
settings_cls: type[BaseSettings],
|
|
94
|
+
raw_config: dict[str, object],
|
|
95
|
+
) -> PydanticBaseSettingsSource:
|
|
96
|
+
"""Create a file source for a specific format.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
settings_cls: Concrete settings class currently being initialized.
|
|
100
|
+
raw_config: ``settings_cls.model_config`` as a regular dictionary.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
Ready-to-use file source instance.
|
|
104
|
+
|
|
105
|
+
"""
|
|
106
|
+
...
|
|
107
|
+
|
|
108
|
+
@classmethod
|
|
109
|
+
def _normalize_paths(cls, paths: object) -> list[Path]:
|
|
110
|
+
"""Normalize paths into a list of ``Path`` objects using ``expanduser()``.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
paths: Single path or sequence of paths.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
List of normalized ``Path`` objects.
|
|
117
|
+
|
|
118
|
+
Raises:
|
|
119
|
+
TypeError: If neither a path nor a list of paths is supplied.
|
|
120
|
+
|
|
121
|
+
"""
|
|
122
|
+
if isinstance(paths, (str, Path)):
|
|
123
|
+
path_items: Sequence[str | Path] = [paths]
|
|
124
|
+
elif isinstance(paths, Sequence):
|
|
125
|
+
path_items = []
|
|
126
|
+
for path in cast("Sequence[object]", paths):
|
|
127
|
+
if not isinstance(path, (str, Path)):
|
|
128
|
+
message = f"Ожидается путь, получено: {type(path).__name__}"
|
|
129
|
+
raise TypeError(message)
|
|
130
|
+
path_items.append(path)
|
|
131
|
+
else:
|
|
132
|
+
message = f"Ожидается путь или список путей, получено: {type(paths).__name__}"
|
|
133
|
+
raise TypeError(message)
|
|
134
|
+
|
|
135
|
+
return [Path(path).expanduser() for path in path_items]
|
|
136
|
+
|
|
137
|
+
@classmethod
|
|
138
|
+
def _validate_paths_exist(cls, paths: list[Path], paths_key: str) -> None:
|
|
139
|
+
"""Check that all configuration paths exist.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
paths: Normalized list of configuration file paths.
|
|
143
|
+
paths_key: ``model_config`` key from which paths were obtained.
|
|
144
|
+
|
|
145
|
+
Raises:
|
|
146
|
+
FileNotFoundError: If any file is missing.
|
|
147
|
+
|
|
148
|
+
"""
|
|
149
|
+
missing = [str(path) for path in paths if not path.is_file()]
|
|
150
|
+
if missing:
|
|
151
|
+
message = f"Файл(ы) конфигурации по ключу '{paths_key}' не найдены: {', '.join(missing)}"
|
|
152
|
+
raise FileNotFoundError(message)
|
|
153
|
+
|
|
154
|
+
@classmethod
|
|
155
|
+
def _model_key_sets(cls, settings_cls: type[BaseSettings]) -> tuple[set[str], set[str]]:
|
|
156
|
+
"""Collect sets of allowed and required model keys.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
settings_cls: Settings class defining the model fields.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
A tuple of ``(allowed_keys, required_keys)``:
|
|
163
|
+
- ``allowed_keys``: aliases and, when enabled, field names;
|
|
164
|
+
- ``required_keys``: required field keys without ``default/default_factory``.
|
|
165
|
+
|
|
166
|
+
"""
|
|
167
|
+
allowed: set[str] = set()
|
|
168
|
+
required: set[str] = set()
|
|
169
|
+
include_name = bool(
|
|
170
|
+
settings_cls.model_config.get("populate_by_name", False)
|
|
171
|
+
or settings_cls.model_config.get("validate_by_name", False)
|
|
172
|
+
)
|
|
173
|
+
for field_name, field in settings_cls.model_fields.items():
|
|
174
|
+
aliases = cast("tuple[list[str], object]", _get_alias_names(field_name, field))[0]
|
|
175
|
+
allowed.update(aliases)
|
|
176
|
+
if include_name:
|
|
177
|
+
allowed.add(field_name)
|
|
178
|
+
if not field.is_required():
|
|
179
|
+
continue
|
|
180
|
+
required.add(aliases[0] if aliases else field_name)
|
|
181
|
+
return allowed, required
|
|
182
|
+
|
|
183
|
+
@classmethod
|
|
184
|
+
def _ensure_no_missing_keys(
|
|
185
|
+
cls,
|
|
186
|
+
source_data: dict[str, object],
|
|
187
|
+
required_keys: set[str],
|
|
188
|
+
provided_keys: set[str],
|
|
189
|
+
) -> None:
|
|
190
|
+
"""Check that required model keys are set in the file or another source.
|
|
191
|
+
|
|
192
|
+
A key is missing only if absent from both the file and all
|
|
193
|
+
non-file sources (env / dotenv / secrets / init). This allows setting
|
|
194
|
+
some required fields through environment variables without duplicating them in the file.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
source_data: Parsed file source data.
|
|
198
|
+
required_keys: Set of required model keys.
|
|
199
|
+
provided_keys: Keys provided by non-file sources.
|
|
200
|
+
|
|
201
|
+
Raises:
|
|
202
|
+
ValueError: If required keys are missing from every source.
|
|
203
|
+
|
|
204
|
+
"""
|
|
205
|
+
missing_keys = sorted(required_keys - set(source_data) - provided_keys)
|
|
206
|
+
if missing_keys:
|
|
207
|
+
message = f"В файле конфигурации отсутствуют ключи: {', '.join(missing_keys)}"
|
|
208
|
+
raise ValueError(message)
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def _ensure_no_unknown_keys(
|
|
212
|
+
cls,
|
|
213
|
+
source_data: dict[str, object],
|
|
214
|
+
allowed_keys: set[str],
|
|
215
|
+
) -> None:
|
|
216
|
+
"""Check that the file contains no unknown keys.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
source_data: Parsed file source data.
|
|
220
|
+
allowed_keys: Set of allowed model keys.
|
|
221
|
+
|
|
222
|
+
Raises:
|
|
223
|
+
ValueError: If the file contains unknown keys.
|
|
224
|
+
|
|
225
|
+
"""
|
|
226
|
+
unknown_keys = sorted(set(source_data) - allowed_keys)
|
|
227
|
+
if unknown_keys:
|
|
228
|
+
message = f"В файле конфигурации найдены неизвестные ключи: {', '.join(unknown_keys)}"
|
|
229
|
+
raise ValueError(message)
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def _collect_provided_keys(
|
|
233
|
+
cls,
|
|
234
|
+
sources: Sequence[PydanticBaseSettingsSource],
|
|
235
|
+
) -> set[str]:
|
|
236
|
+
"""Collect top-level keys provided by non-file sources.
|
|
237
|
+
|
|
238
|
+
Ensure required fields supplied through env / dotenv / secrets / init
|
|
239
|
+
are not considered missing when validating the file configuration.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
sources: Non-file settings sources.
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
Set of keys provided by the supplied sources.
|
|
246
|
+
|
|
247
|
+
"""
|
|
248
|
+
provided: set[str] = set()
|
|
249
|
+
for source in sources:
|
|
250
|
+
provided.update(cast("dict[str, object]", source()))
|
|
251
|
+
return provided
|
|
252
|
+
|
|
253
|
+
@classmethod
|
|
254
|
+
def _validate_file_keys_consistency(
|
|
255
|
+
cls,
|
|
256
|
+
settings_cls: type[BaseSettings],
|
|
257
|
+
file_source: PydanticBaseSettingsSource,
|
|
258
|
+
*,
|
|
259
|
+
validate_required_keys: bool,
|
|
260
|
+
validate_unknown_keys: bool,
|
|
261
|
+
provided_keys: set[str],
|
|
262
|
+
) -> None:
|
|
263
|
+
"""Validate required and unknown keys in the file.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
settings_cls: Settings class used to validate keys.
|
|
267
|
+
file_source: File source that returns parsed data.
|
|
268
|
+
validate_required_keys: Whether required key validation is enabled.
|
|
269
|
+
validate_unknown_keys: Whether unknown key validation is enabled.
|
|
270
|
+
provided_keys: Keys provided by non-file sources.
|
|
271
|
+
|
|
272
|
+
Raises:
|
|
273
|
+
ValueError: If required keys are missing or unknown keys are present.
|
|
274
|
+
|
|
275
|
+
"""
|
|
276
|
+
source_data = cast("dict[str, object]", file_source())
|
|
277
|
+
allowed_keys, required_keys = cls._model_key_sets(settings_cls)
|
|
278
|
+
if validate_required_keys:
|
|
279
|
+
cls._ensure_no_missing_keys(source_data, required_keys, provided_keys)
|
|
280
|
+
if validate_unknown_keys:
|
|
281
|
+
cls._ensure_no_unknown_keys(source_data, allowed_keys)
|
|
282
|
+
|
|
283
|
+
@classmethod
|
|
284
|
+
def settings_customise_sources(
|
|
285
|
+
cls,
|
|
286
|
+
settings_cls: type[BaseSettings],
|
|
287
|
+
init_settings: PydanticBaseSettingsSource,
|
|
288
|
+
env_settings: PydanticBaseSettingsSource,
|
|
289
|
+
dotenv_settings: PydanticBaseSettingsSource,
|
|
290
|
+
file_secret_settings: PydanticBaseSettingsSource,
|
|
291
|
+
) -> tuple[PydanticBaseSettingsSource, ...]:
|
|
292
|
+
"""Arrange sources by priority and validate the file configuration.
|
|
293
|
+
|
|
294
|
+
:param settings_cls: concrete settings class.
|
|
295
|
+
:param init_settings: values from the model constructor.
|
|
296
|
+
:param env_settings: environment variable values.
|
|
297
|
+
:param dotenv_settings: values from dotenv files.
|
|
298
|
+
:param file_secret_settings: secrets from a directory.
|
|
299
|
+
:return: sources in env, dotenv, secrets, file, init order.
|
|
300
|
+
:raises ValueError: if no path is set or file keys do not match the model.
|
|
301
|
+
:raises FileNotFoundError: if the settings file is missing.
|
|
302
|
+
:raises TypeError: if a path has an unsupported type.
|
|
303
|
+
"""
|
|
304
|
+
paths_key = cls._paths_config_key
|
|
305
|
+
|
|
306
|
+
raw_config = cast("dict[str, object]", settings_cls.model_config)
|
|
307
|
+
if not raw_config.get(paths_key):
|
|
308
|
+
missing_msg = cls._missing_paths_error
|
|
309
|
+
raise ValueError(missing_msg)
|
|
310
|
+
|
|
311
|
+
paths = cls._normalize_paths(raw_config[paths_key])
|
|
312
|
+
cls._validate_paths_exist(paths, paths_key)
|
|
313
|
+
|
|
314
|
+
validate_required_keys = bool(raw_config.get(cls._validate_required_keys_config_key, True))
|
|
315
|
+
validate_unknown_keys = bool(raw_config.get(cls._validate_unknown_keys_config_key, True))
|
|
316
|
+
file_source = cls._build_file_source(settings_cls, raw_config)
|
|
317
|
+
if not validate_unknown_keys:
|
|
318
|
+
allowed_keys, _ = cls._model_key_sets(settings_cls)
|
|
319
|
+
filterable_source = cast("SupportsUnknownKeysFiltering", file_source)
|
|
320
|
+
filterable_source.set_unknown_keys_filter(allowed_keys)
|
|
321
|
+
provided_keys = cls._collect_provided_keys(
|
|
322
|
+
(env_settings, dotenv_settings, file_secret_settings, init_settings),
|
|
323
|
+
)
|
|
324
|
+
cls._validate_file_keys_consistency(
|
|
325
|
+
settings_cls,
|
|
326
|
+
file_source,
|
|
327
|
+
validate_required_keys=validate_required_keys,
|
|
328
|
+
validate_unknown_keys=validate_unknown_keys,
|
|
329
|
+
provided_keys=provided_keys,
|
|
330
|
+
)
|
|
331
|
+
return (
|
|
332
|
+
env_settings,
|
|
333
|
+
dotenv_settings,
|
|
334
|
+
file_secret_settings,
|
|
335
|
+
file_source,
|
|
336
|
+
init_settings,
|
|
337
|
+
)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, ClassVar, cast
|
|
4
|
+
|
|
5
|
+
from pydantic_settings.sources import JsonConfigSettingsSource
|
|
6
|
+
|
|
7
|
+
from .base_source_type import FileTypeBaseSettings, UnknownKeysFilteringMixin
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from importlib.resources.abc import Traversable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class JsonBaseSettings(FileTypeBaseSettings):
|
|
17
|
+
"""Base class for settings loaded from json files.
|
|
18
|
+
|
|
19
|
+
Supply a file path or sequence of paths in the ``json_file`` property
|
|
20
|
+
|
|
21
|
+
>>> class MySettings(JsonBaseSettings):
|
|
22
|
+
>>> ... # settings
|
|
23
|
+
>>> model_config = SettingsConfigDict(json_file="config.json")
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
_paths_config_key: ClassVar[str] = "json_file"
|
|
27
|
+
_encoding_config_key: ClassVar[str] = "json_file_encoding"
|
|
28
|
+
_missing_paths_error: ClassVar[str] = "Не указан путь до json файла с настройками"
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def _build_file_source(
|
|
32
|
+
cls,
|
|
33
|
+
settings_cls: type[BaseSettings],
|
|
34
|
+
raw_config: dict[str, object],
|
|
35
|
+
) -> PydanticBaseSettingsSource:
|
|
36
|
+
return StrictJsonConfigSettingsSource(
|
|
37
|
+
settings_cls=settings_cls,
|
|
38
|
+
json_file=cls._normalize_paths(raw_config.get(cls._paths_config_key)),
|
|
39
|
+
json_file_encoding=cast("str | None", raw_config.get(cls._encoding_config_key)),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class StrictJsonConfigSettingsSource(UnknownKeysFilteringMixin, JsonConfigSettingsSource):
|
|
44
|
+
"""Strict JSON source with an explicit error for non-dictionaries.
|
|
45
|
+
|
|
46
|
+
Raises:
|
|
47
|
+
TypeError: If the JSON root is not a ``dict``.
|
|
48
|
+
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def _read_file(self, file_path: Path | Traversable) -> dict[str, object]:
|
|
52
|
+
data = cast("object", super()._read_file(file_path))
|
|
53
|
+
if not isinstance(data, dict):
|
|
54
|
+
message = f"Файл конфигурации не является dict: {file_path}"
|
|
55
|
+
raise TypeError(message)
|
|
56
|
+
return cast("dict[str, object]", data)
|
|
57
|
+
|
|
58
|
+
def __call__(self) -> dict[str, object]:
|
|
59
|
+
"""Return settings values with the filter applied.
|
|
60
|
+
|
|
61
|
+
:return: file source values.
|
|
62
|
+
"""
|
|
63
|
+
return self.apply_unknown_keys_filter(cast("dict[str, object]", super().__call__()))
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, ClassVar, cast
|
|
4
|
+
|
|
5
|
+
from pydantic_settings.sources import TomlConfigSettingsSource
|
|
6
|
+
|
|
7
|
+
from .base_source_type import FileTypeBaseSettings, UnknownKeysFilteringMixin
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TomlBaseSettings(FileTypeBaseSettings):
|
|
14
|
+
"""Base class for settings loaded from toml files.
|
|
15
|
+
|
|
16
|
+
Supply a file path or sequence of paths in the ``toml_file`` property
|
|
17
|
+
|
|
18
|
+
>>> class MySettings(TomlBaseSettings):
|
|
19
|
+
>>> ... # settings
|
|
20
|
+
>>> model_config = SettingsConfigDict(toml_file="config.toml")
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
_paths_config_key: ClassVar[str] = "toml_file"
|
|
24
|
+
_encoding_config_key: ClassVar[str | None] = None
|
|
25
|
+
_missing_paths_error: ClassVar[str] = "Не указан путь до toml файла с настройками"
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def _build_file_source(
|
|
29
|
+
cls,
|
|
30
|
+
settings_cls: type[BaseSettings],
|
|
31
|
+
raw_config: dict[str, object],
|
|
32
|
+
) -> PydanticBaseSettingsSource:
|
|
33
|
+
return StrictTomlConfigSettingsSource(
|
|
34
|
+
settings_cls=settings_cls,
|
|
35
|
+
toml_file=cls._normalize_paths(raw_config.get(cls._paths_config_key)),
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class StrictTomlConfigSettingsSource(UnknownKeysFilteringMixin, TomlConfigSettingsSource):
|
|
40
|
+
"""TOML source that supports filtering unknown keys."""
|
|
41
|
+
|
|
42
|
+
def __call__(self) -> dict[str, object]:
|
|
43
|
+
"""Return settings values with the filter applied.
|
|
44
|
+
|
|
45
|
+
:return: file source values.
|
|
46
|
+
"""
|
|
47
|
+
return self.apply_unknown_keys_filter(cast("dict[str, object]", super().__call__()))
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, ClassVar, cast
|
|
4
|
+
|
|
5
|
+
from pydantic_settings.sources import YamlConfigSettingsSource
|
|
6
|
+
|
|
7
|
+
from .base_source_type import FileTypeBaseSettings, UnknownKeysFilteringMixin
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from importlib.resources.abc import Traversable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class YamlBaseSettings(FileTypeBaseSettings):
|
|
17
|
+
"""Base class for settings loaded from yaml files.
|
|
18
|
+
|
|
19
|
+
Supply a file path or sequence of paths in the ``yaml_file`` property
|
|
20
|
+
|
|
21
|
+
>>> class MySettings(YamlBaseSettings):
|
|
22
|
+
>>> ... # settings
|
|
23
|
+
>>> model_config = SettingsConfigDict(yaml_file="config.yaml")
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
_paths_config_key: ClassVar[str] = "yaml_file"
|
|
27
|
+
_encoding_config_key: ClassVar[str] = "yaml_file_encoding"
|
|
28
|
+
_missing_paths_error: ClassVar[str] = "Не указан путь до yaml файла с настройками"
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def _build_file_source(
|
|
32
|
+
cls,
|
|
33
|
+
settings_cls: type[BaseSettings],
|
|
34
|
+
raw_config: dict[str, object],
|
|
35
|
+
) -> PydanticBaseSettingsSource:
|
|
36
|
+
try:
|
|
37
|
+
return StrictYamlConfigSettingsSource(
|
|
38
|
+
settings_cls=settings_cls,
|
|
39
|
+
yaml_file=cls._normalize_paths(raw_config.get(cls._paths_config_key)),
|
|
40
|
+
yaml_file_encoding=cast("str | None", raw_config.get(cls._encoding_config_key)),
|
|
41
|
+
)
|
|
42
|
+
except ImportError as e:
|
|
43
|
+
if "PyYAML is not installed" in str(e):
|
|
44
|
+
message = (
|
|
45
|
+
"Для загрузки YAML настроек установите зависимость: "
|
|
46
|
+
'pip install "cloudru-qa-pydantic-extensions[yaml]"'
|
|
47
|
+
)
|
|
48
|
+
raise ImportError(message) from e
|
|
49
|
+
raise
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class StrictYamlConfigSettingsSource(UnknownKeysFilteringMixin, YamlConfigSettingsSource):
|
|
53
|
+
"""Strict YAML source with an explicit error for non-dictionaries.
|
|
54
|
+
|
|
55
|
+
Raises:
|
|
56
|
+
TypeError: If the YAML root is not a ``dict``.
|
|
57
|
+
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def _read_file(self, file_path: Path | Traversable) -> dict[str, object]:
|
|
61
|
+
data = cast("object", super()._read_file(file_path))
|
|
62
|
+
if not isinstance(data, dict):
|
|
63
|
+
message = f"Файл конфигурации не является dict: {file_path}"
|
|
64
|
+
raise TypeError(message)
|
|
65
|
+
return cast("dict[str, object]", data)
|
|
66
|
+
|
|
67
|
+
def __call__(self) -> dict[str, object]:
|
|
68
|
+
"""Return settings values with the filter applied.
|
|
69
|
+
|
|
70
|
+
:return: file source values.
|
|
71
|
+
"""
|
|
72
|
+
return self.apply_unknown_keys_filter(cast("dict[str, object]", super().__call__()))
|