Environment Examples

This section contains examples demonstrating the environment management capabilities of True Storage.

Basic Environment Usage

The following example shows basic environment variable handling:

Basic Environment Usage
 1"""Basic environment variable management demo.
 2
 3This demo shows basic environment variable operations using the Environment class.
 4"""
 5
 6from true_storage.env import Environment
 7
 8def main():
 9    """Run the basic environment demo."""
10    print("\n=== Basic Environment Demo ===\n")
11
12    # Create environment instance
13    env = Environment()
14
15    # Set some basic variables
16    env.set({
17        'APP_NAME': 'DemoApp',
18        'VERSION': '1.0.0',
19        'DEBUG': 'true'
20    })
21
22    # Get variables
23    print("1. Getting Variables")
24    print("-------------------")
25    print(f"APP_NAME: {env.get('APP_NAME')}")
26    print(f"VERSION: {env.get('VERSION')}")
27    print(f"DEBUG: {env.get('DEBUG')}")
28    print(f"UNDEFINED: {env.get('UNDEFINED', 'default_value')}")  # With default value
29
30    # Dictionary-style access
31    print("\n2. Dictionary-style Access")
32    print("-------------------------")
33    env['PORT'] = '8080'  # Set using dict style
34    print(f"PORT: {env['PORT']}")  # Get using dict style
35    del env['PORT']  # Delete using dict style
36    print(f"PORT (deleted): {env.get('PORT', 'not found')}")
37
38    # Environment information
39    print("\n3. Environment Information")
40    print("-------------------------")
41    print(f"Number of variables: {len(env)}")
42    print(f"All variables: {env.variables}")
43
44if __name__ == "__main__":
45    main()
Key features demonstrated:
  • Loading environment variables

  • Accessing environment values

  • Environment variable validation

  • Default values

Mode-Specific Configuration

This example demonstrates mode-specific environment configurations:

Mode-Specific Environment Configuration
 1"""Mode-specific environment variable management demo.
 2
 3This demo shows how to use mode-specific environment variables and the mode decorator.
 4"""
 5
 6from true_storage.env import Environment, MODES
 7
 8def main():
 9    """Run the mode-specific environment demo."""
10    print("\n=== Mode-Specific Environment Demo ===\n")
11
12    # Create environment instance
13    env = Environment()
14
15    print("1. Setting Mode-Specific Variables")
16    print("--------------------------------")
17    # Set variables with different mode access
18    env.set({'APP_NAME': 'TrueStorage'}, modes=[MODES.ALL])  # Available in all modes
19    env.set({'DB_URL': 'localhost:5432'}, modes=[MODES.DEV, MODES.TEST])  # Dev and test
20    env.set({'API_KEY': 'test-key-123'}, modes=[MODES.TEST])  # Only in test
21    env.set({'PROD_SECRET': 'secret-123'}, modes=[MODES.PROD])  # Only in production
22
23    # Define mode-specific functions
24    @env.mark(MODES.TEST)
25    def get_test_config():
26        """Get test configuration."""
27        return {
28            'db_url': env.get('DB_URL'),
29            'api_key': env.get('API_KEY')
30        }
31
32    @env.mark(MODES.PROD)
33    def get_prod_config():
34        """Get production configuration."""
35        return {
36            'app_name': env.get('APP_NAME'),
37            'secret': env.get('PROD_SECRET')
38        }
39
40    print("\n2. Accessing Variables in Different Modes")
41    print("---------------------------------------")
42
43    # Test DEV mode
44    env.mode = MODES.DEV
45    print(f"DEV Mode:")
46    print(f"  APP_NAME: {env.get('APP_NAME')}")  # Should work
47    print(f"  DB_URL: {env.get('DB_URL')}")      # Should work
48    try:
49        print(f"  API_KEY: {env.get('API_KEY')}")  # Should fail
50    except Exception as e:
51        print(f"  API_KEY access failed (expected): {e}")
52
53    # Test TEST mode
54    env.mode = MODES.TEST
55    print(f"\nTEST Mode:")
56    print(f"  APP_NAME: {env.get('APP_NAME')}")  # Should work
57    print(f"  DB_URL: {env.get('DB_URL')}")      # Should work
58    print(f"  API_KEY: {env.get('API_KEY')}")    # Should work
59    try:
60        print(f"  PROD_SECRET: {env.get('PROD_SECRET')}")  # Should fail
61    except Exception as e:
62        print(f"  PROD_SECRET access failed (expected): {e}")
63
64    print("\n3. Using Mode-Specific Functions")
65    print("------------------------------")
66    try:
67        # Try to get test config in TEST mode
68        env.mode = MODES.TEST
69        test_config = get_test_config()
70        print(f"Test Config (TEST mode): {test_config}")
71
72        # Try to get prod config in TEST mode (should fail)
73        prod_config = get_prod_config()
74        print(f"Prod Config (TEST mode): {prod_config}")
75    except Exception as e:
76        print(f"Prod config in TEST mode failed (expected): {e}")
77
78    try:
79        # Try to get prod config in PROD mode
80        env.mode = MODES.PROD
81        prod_config = get_prod_config()
82        print(f"\nProd Config (PROD mode): {prod_config}")
83
84        # Try to get test config in PROD mode (should fail)
85        test_config = get_test_config()
86        print(f"Test Config (PROD mode): {test_config}")
87    except Exception as e:
88        print(f"Test config in PROD mode failed (expected): {e}")
89
90if __name__ == "__main__":
91    main()
Key features demonstrated:
  • Development vs Production modes

  • Mode-specific variables

  • Environment inheritance

  • Configuration overrides

Environment Snapshots

The following example shows how to work with environment snapshots:

Environment Snapshots
 1"""Environment snapshot and rollback demo.
 2
 3This demo shows how to use environment snapshots for backup and rollback.
 4"""
 5
 6from true_storage.env import Environment, MODES
 7
 8def main():
 9    """Run the environment snapshot demo."""
10    print("\n=== Environment Snapshot Demo ===\n")
11
12    # Create environment instance
13    env = Environment()
14
15    print("1. Initial Setup")
16    print("--------------")
17    # Set initial variables
18    env.set({
19        'APP_NAME': 'TrueStorage',
20        'VERSION': '1.0.0',
21        'DEBUG': 'false'
22    })
23
24    # Display initial state
25    print("Initial variables:")
26    print(f"  APP_NAME: {env.get('APP_NAME')}")
27    print(f"  VERSION: {env.get('VERSION')}")
28    print(f"  DEBUG: {env.get('DEBUG')}")
29
30    print("\n2. Creating Snapshot")
31    print("------------------")
32    # Create a snapshot
33    snapshot = env.create_snapshot()
34    print(f"Snapshot created at: {snapshot.timestamp}")
35    print(f"Variables in snapshot: {len(snapshot.variables)}")
36
37    print("\n3. Making Changes")
38    print("---------------")
39    # Make some changes
40    env.set({
41        'APP_NAME': 'TrueStorage-Dev',
42        'DEBUG': 'true',
43        'NEW_VAR': 'new-value'
44    })
45
46    print("Variables after changes:")
47    print(f"  APP_NAME: {env.get('APP_NAME')}")
48    print(f"  DEBUG: {env.get('DEBUG')}")
49    print(f"  NEW_VAR: {env.get('NEW_VAR')}")
50
51    print("\n4. Rolling Back")
52    print("-------------")
53    # Roll back to snapshot
54    env.rollback(snapshot)
55
56    print("Variables after rollback:")
57    print(f"  APP_NAME: {env.get('APP_NAME')}")
58    print(f"  VERSION: {env.get('VERSION')}")
59    print(f"  DEBUG: {env.get('DEBUG')}")
60    print(f"  NEW_VAR: {env.get('NEW_VAR', 'Not Found')}")
61
62    print("\n5. Mode-Specific Snapshots")
63    print("-----------------------")
64    # Set mode-specific variables
65    env.set({'TEST_VAR': 'test-value'}, modes=[MODES.TEST])
66    env.set({'PROD_VAR': 'prod-value'}, modes=[MODES.PROD])
67
68    # Create new snapshot
69    mode_snapshot = env.create_snapshot()
70
71    # Make mode-specific changes
72    env.set({'TEST_VAR': 'modified-test'}, modes=[MODES.TEST])
73    env.set({'PROD_VAR': 'modified-prod'}, modes=[MODES.PROD])
74
75    print("Variables before mode-specific rollback:")
76    env.mode = MODES.TEST
77    print(f"  TEST_VAR (TEST mode): {env.get('TEST_VAR', 'Not Found')}")
78    env.mode = MODES.PROD
79    print(f"  PROD_VAR (PROD mode): {env.get('PROD_VAR', 'Not Found')}")
80
81    # Roll back mode-specific changes
82    env.rollback(mode_snapshot)
83
84    print("\nVariables after mode-specific rollback:")
85    env.mode = MODES.TEST
86    print(f"  TEST_VAR (TEST mode): {env.get('TEST_VAR', 'Not Found')}")
87    env.mode = MODES.PROD
88    print(f"  PROD_VAR (PROD mode): {env.get('PROD_VAR', 'Not Found')}")
89
90if __name__ == "__main__":
91    main()
Key features demonstrated:
  • Creating environment snapshots

  • Restoring from snapshots

  • Snapshot comparison

  • State management

Advanced Environment Features

This example demonstrates advanced environment management features:

Advanced Environment Features
  1"""Advanced environment management features demo.
  2
  3This demo shows advanced features like validation, filtering, and inheritance.
  4"""
  5
  6from true_storage.env import Environment, MODES, EnvValidator
  7
  8def main():
  9    """Run the advanced environment features demo."""
 10    print("\n=== Advanced Environment Features Demo ===\n")
 11
 12    print("1. Environment Validation")
 13    print("----------------------")
 14    # Create environment with validation
 15    schema = {
 16        'PORT': int,
 17        'DEBUG': bool,
 18        'API_URL': str,
 19        'MAX_CONNECTIONS': int
 20    }
 21    env = Environment(validator=EnvValidator(schema))
 22
 23    # Set valid values
 24    env.set({
 25        'PORT': '8080',           # Will be converted to int
 26        'DEBUG': 'true',          # Will be converted to bool
 27        'API_URL': 'http://api',  # Stays as string
 28        'MAX_CONNECTIONS': '100'  # Will be converted to int
 29    })
 30
 31    print("Valid values set successfully:")
 32    print(f"  PORT: {env.get('PORT')} (type: {type(env.get('PORT'))})")
 33    print(f"  DEBUG: {env.get('DEBUG')} (type: {type(env.get('DEBUG'))})")
 34    print(f"  API_URL: {env.get('API_URL')} (type: {type(env.get('API_URL'))})")
 35    print(f"  MAX_CONNECTIONS: {env.get('MAX_CONNECTIONS')} (type: {type(env.get('MAX_CONNECTIONS'))})")
 36
 37    # Try setting invalid values
 38    print("\nTrying to set invalid values:")
 39    try:
 40        env.set({'PORT': 'invalid_port'})  # Should fail validation
 41    except Exception as e:
 42        print(f"  PORT validation failed (expected): {e}")
 43
 44    print("\n2. Environment Inheritance")
 45    print("-----------------------")
 46    # Create parent environment
 47    parent_env = Environment()
 48    parent_env.set({
 49        'PARENT_VAR': 'parent_value',
 50        'SHARED_VAR': 'parent_version'
 51    })
 52
 53    # Create child environment
 54    child_env = Environment(parent=parent_env)
 55    child_env.set({'CHILD_VAR': 'child_value'})
 56    child_env.set({'SHARED_VAR': 'child_version'})  # Override parent
 57
 58    print("Parent environment:")
 59    print(f"  PARENT_VAR: {parent_env.get('PARENT_VAR')}")
 60    print(f"  SHARED_VAR: {parent_env.get('SHARED_VAR')}")
 61
 62    print("\nChild environment:")
 63    print(f"  PARENT_VAR: {child_env.get('PARENT_VAR')}") # Inherited
 64    print(f"  CHILD_VAR: {child_env.get('CHILD_VAR')}")   # Own variable
 65    print(f"  SHARED_VAR: {child_env.get('SHARED_VAR')}")  # Overridden
 66
 67    print("\n3. Variable Filtering")
 68    print("------------------")
 69    # Set some variables for filtering
 70    env.set({
 71        'DB_HOST': 'localhost',
 72        'DB_PORT': '5432',
 73        'DB_NAME': 'mydb',
 74        'API_KEY': 'secret',
 75        'API_VERSION': 'v1'
 76    })
 77
 78    # Filter by prefix
 79    db_vars = env.filter('DB_')
 80    api_vars = env.filter('API_')
 81
 82    print("Database-related variables:")
 83    for key, value in db_vars.items():
 84        print(f"  {key}: {value}")
 85
 86    print("\nAPI-related variables:")
 87    for key, value in api_vars.items():
 88        print(f"  {key}: {value}")
 89
 90    print("\n4. Mode-Specific Inheritance")
 91    print("-------------------------")
 92    # Set mode-specific variables in parent
 93    parent_env.set({'MODE_VAR': 'parent_mode_var'}, modes=[MODES.TEST])
 94
 95    # Child inherits mode restrictions
 96    print("Mode-specific inheritance:")
 97    child_env.mode = MODES.TEST
 98    print(f"  MODE_VAR in TEST mode: {child_env.get('MODE_VAR')}")
 99
100    child_env.mode = MODES.DEV
101    try:
102        print(f"  MODE_VAR in DEV mode: {child_env.get('MODE_VAR')}")
103    except Exception as e:
104        print(f"  MODE_VAR access failed in DEV mode (expected): {e}")
105
106if __name__ == "__main__":
107    main()
Key features demonstrated:
  • Environment validation

  • Custom type conversion

  • Environment inheritance

  • Dynamic configuration