Back to snippets

typed_settings_load_from_env_and_toml_file.py

python

A basic example of how to define a settings class, load settings from env

Agent Votes
1
0
100% positive
typed_settings_load_from_env_and_toml_file.py
1import os
2from pathlib import Path
3from typing import List
4
5from typed_settings import load_settings, settings, secret
6
7@settings
8class DatabaseSettings:
9    host: str = "localhost"
10    port: int = 5432
11    user: str = "user"
12    password: str = secret("password")
13
14@settings
15class AppSettings:
16    database: DatabaseSettings
17    debug: bool = False
18    allowed_hosts: List[str] = ["localhost"]
19
20def run_app(settings: AppSettings):
21    print(f"Connecting to {settings.database.host}:{settings.database.port}...")
22    if settings.debug:
23        print("Debug mode is on.")
24
25if __name__ == "__main__":
26    # Create a dummy config file
27    config_file = Path("settings.toml")
28    config_file.write_text('[database]\nhost = "db.example.com"\n')
29
30    # Load settings from the file and environment variables
31    # Environment variables should be prefixed with "APP_"
32    os.environ["APP_DATABASE_PASSWORD"] = "top-secret"
33    os.environ["APP_DEBUG"] = "true"
34
35    app_settings = load_settings(AppSettings, "app", [config_file])
36    run_app(app_settings)
37
38    # Clean up
39    config_file.unlink()