Validation ExampleΒΆ

Shows how to use validators.

 1"""
 2Example demonstrating configuration validation.
 3
 4This example shows how to use validators to ensure configuration values
 5meet your requirements.
 6
 7Run with:
 8    python validation_example.py
 9    python validation_example.py --port 99999  # Will fail validation
10    python validation_example.py -cv  # Check variables
11"""
12
13import os
14import sys
15from dataclasses import dataclass, field
16
17from varlord import Config, sources
18from varlord.validators import ValidationError, validate_range, validate_regex
19
20# Set environment variables for testing
21os.environ["APP_PORT"] = "9000"
22os.environ["APP_HOST"] = "0.0.0.0"
23
24
25@dataclass(frozen=True)
26class AppConfig:
27    """Application configuration with validation."""
28
29    host: str = field(default="127.0.0.1", metadata={"description": "Server host address"})
30    port: int = field(default=8000, metadata={"description": "Server port number"})
31
32    def __post_init__(self):
33        """Validate configuration after initialization."""
34        # Validate port range
35        validate_range(self.port, min=1, max=65535)
36        # Validate host format (simple IP check)
37        validate_regex(self.host, r"^\d+\.\d+\.\d+\.\d+$")
38
39
40def main():
41    """Main function."""
42    cfg = Config(
43        model=AppConfig,
44        sources=[
45            sources.Env(),  # Model defaults applied automatically, model auto-injected
46            sources.CLI(),  # CLI arguments can override env vars
47        ],
48    )
49
50    # Handle CLI commands
51    cfg.handle_cli_commands()
52
53    try:
54        app = cfg.load()
55        print("βœ… Configuration loaded and validated successfully!")
56        print(f"   Host: {app.host}")
57        print(f"   Port: {app.port}")
58    except ValidationError as e:
59        print(f"❌ Validation error: {e.key} = {e.value}")
60        print(f"   {e.message}")
61        sys.exit(1)
62    except Exception as e:
63        print(f"❌ Error: {e}")
64        sys.exit(1)
65
66
67if __name__ == "__main__":
68    main()