-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_models.py
More file actions
43 lines (28 loc) · 1.05 KB
/
config_models.py
File metadata and controls
43 lines (28 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from __future__ import annotations
from pathlib import Path
from typing import List, Type, TypeVar
import json
import yaml
from pydantic import BaseModel, PositiveFloat, conint, IPvAnyAddress
class ShipConfig(BaseModel):
"""Конфигурация корабля."""
name: str
max_speed: PositiveFloat
capacity: conint(ge=0)
class NetworkConfig(BaseModel):
"""Параметры сети."""
host: str
port: conint(gt=0, lt=65536)
class SecurityConfig(BaseModel):
"""Настройки безопасности."""
use_tls: bool = False
allowed_ips: List[IPvAnyAddress] = []
T = TypeVar("T", bound=BaseModel)
def load_config(path: Path, model: Type[T]) -> T:
"""Загрузить конфигурацию из JSON или YAML с валидацией."""
with path.open() as f:
if path.suffix.lower() in {".yaml", ".yml"}:
data = yaml.safe_load(f)
else:
data = json.load(f)
return model.model_validate(data) if hasattr(model, 'model_validate') else model.parse_obj(data)