### Quick Start: Define Config with Environment Variables and Computed Values (Python) Source: https://github.com/tsv1/cabina/blob/main/README.md A minimal example demonstrating how cabina parses environment variables, uses defaults, and computes values. It defines API host and port, and a computed API URL. It shows basic usage and printing the configuration. ```python import cabina from cabina import computed, env class Config(cabina.Config): class Main(cabina.Section): API_HOST: str = env.str("API_HOST", default="localhost") API_PORT: int = env.int("API_PORT", default=8080) @computed def API_URL(cls) -> str: return f"http://{cls.API_HOST}:{cls.API_PORT}" # Usage assert Config.Main.API_URL == "http://localhost:8080" assert Config["Main"]["API_URL"] == "http://localhost:8080" # Print print(Config) # class : # class
: # API_HOST = 'localhost' # API_PORT = 8080 # API_URL = 'http://localhost:8080' ``` -------------------------------- ### Install Cabina Python Package Source: https://github.com/tsv1/cabina/blob/main/README.md Install the cabina library using pip. This is the first step to using cabina for managing configurations. ```shell pip3 install cabina ``` -------------------------------- ### Configuration Inheritance with Cabina (Python) Source: https://context7.com/tsv1/cabina/llms.txt Demonstrates configuration inheritance in Cabina, where base configurations can be extended to create specialized variants. The example defines a base `Config` class with nested `App` and `Database` sections, setting default values for production environments. This pattern facilitates managing different configurations for various deployment stages or environments. ```python import cabina from cabina import env # Base production configuration class Config(cabina.Config): class App(cabina.Section): NAME: str = "MyApp" VERSION: str = "1.0.0" DEBUG: bool = False class Database(cabina.Section): HOST: str = "prod-db.example.com" PORT: int = 5432 POOL_SIZE: int = 20 ``` -------------------------------- ### Lazy Environment Variable Evaluation with Cabina (Python) Source: https://context7.com/tsv1/cabina/llms.txt Demonstrates lazy evaluation of environment variables using `cabina.lazy_env`. This approach defers the reading and parsing of environment variables until they are explicitly accessed, improving performance and allowing for more granular error handling. The example also shows how to prefetch and validate all configuration values at once using `Config.prefetch()`. ```python import os import cabina from cabina import lazy_env os.environ['API_KEY'] = 'secret-key-123' os.environ['DEBUG'] = 'true' # OPTIONAL_FEATURE not set class Config(cabina.Config, cabina.Section): API_KEY: str = lazy_env.str("API_KEY") DEBUG: bool = lazy_env.bool("DEBUG") OPTIONAL_FEATURE: str = lazy_env.str("OPTIONAL_FEATURE", default="disabled") # Values are not evaluated until accessed print(Config.API_KEY) # Now the environment variable is read: 'secret-key-123' print(Config.DEBUG) # Output: True # Prefetch all values to validate configuration early try: Config.prefetch() print("Configuration is valid") except cabina.ConfigEnvError as e: print(f"Configuration error: {e}") ``` -------------------------------- ### Iterate Configuration Values and Use Dictionary Operations with Cabina Source: https://context7.com/tsv1/cabina/llms.txt Illustrates how to treat a Cabina configuration object like a dictionary. It shows iterating over keys, values, and items, checking for key membership, and retrieving values with a default using `get()`. ```python import os import cabina from cabina import env os.environ['HOST'] = 'localhost' os.environ['PORT'] = '8000' os.environ['DEBUG'] = 'true' class Config(cabina.Config, cabina.Section): HOST: str = env.str("HOST") PORT: int = env.int("PORT") DEBUG: bool = env.bool("DEBUG") for key in Config.keys(): print(key) for value in Config.values(): print(value) for key, value in Config.items(): print(f"{key} = {value}") print("HOST" in Config) # Output: True print("UNKNOWN" in Config) # Output: False print(Config.get("HOST")) # Output: 'localhost' print(Config.get("MISSING", "N/A")) # Output: 'N/A' ``` -------------------------------- ### Default Values for Environment Variables (Python) Source: https://github.com/tsv1/cabina/blob/main/README.md Shows how to provide default values for configuration settings if the corresponding environment variable is not set. This example sets defaults for API_HOST and API_PORT. ```python import cabina from cabina import env class Config(cabina.Config, cabina.Section): API_HOST = env.str("API_HOST", default="localhost") API_PORT = env.int("API_PORT", default=8080) assert Config.API_HOST == "127.0.0.1" assert Config.API_PORT == 8080 ``` -------------------------------- ### Custom Parsers for Environment Variables (Python) Source: https://github.com/tsv1/cabina/blob/main/README.md Explains how to use custom parsing functions with `cabina.env` to handle special data formats. This example uses `pytimeparse` to parse a duration string from an environment variable. ```python import cabina from cabina import env from pytimeparse import parse as parse_duration class Config(cabina.Config, cabina.Section): HTTP_TIMEOUT: int = env("HTTP_TIMEOUT", parser=parse_duration) assert Config.HTTP_TIMEOUT == 10 ``` -------------------------------- ### Environment Variable Prefixing with Cabina (Python) Source: https://context7.com/tsv1/cabina/llms.txt Shows how to group related environment variables using a common prefix with `cabina.Environment(prefix=...)`. This avoids naming collisions when multiple applications or libraries use environment variables. The example defines a `Config` class where variables like `HOST`, `PORT`, and `DEBUG` are read from `MYAPP_HOST`, `MYAPP_PORT`, and `MYAPP_DEBUG` respectively. ```python import os import cabina # Set prefixed environment variables os.environ['MYAPP_HOST'] = 'localhost' os.environ['MYAPP_PORT'] = '8000' os.environ['MYAPP_DEBUG'] = 'yes' # Create environment with prefix env = cabina.Environment(prefix="MYAPP_") class Config(cabina.Config, cabina.Section): HOST: str = env.str("HOST") # Reads MYAPP_HOST PORT: int = env.int("PORT") # Reads MYAPP_PORT DEBUG: bool = env.bool("DEBUG") # Reads MYAPP_DEBUG # Access configuration print(Config.HOST) # Output: 'localhost' print(Config.PORT) # Output: 8000 print(Config.DEBUG) # Output: True ``` -------------------------------- ### Computed Values with @computed Decorator (Python) Source: https://github.com/tsv1/cabina/blob/main/README.md Illustrates how to define dynamic or derived configuration values using the `@computed` decorator in Python. This example computes an API URL based on API host and port environment variables. ```python import cabina from cabina import computed, env class Config(cabina.Config, cabina.Section): API_HOST: str = env.str("API_HOST") API_PORT: int = env.int("API_PORT") @computed def API_URL(cls) -> str: return f"http://{cls.API_HOST}:{cls.API_PORT}" assert Config.API_URL == "http://localhost:8080" ``` -------------------------------- ### Raw Environment Variable Access in Cabina (Python) Source: https://context7.com/tsv1/cabina/llms.txt Explains how to retrieve raw environment variable values without automatic whitespace trimming using `cabina.env.raw`. This is useful when exact string values, including leading/trailing spaces, need to be preserved. The example contrasts `env.raw()` with `env.str()` to show the difference in output. ```python import os import cabina from cabina import env # Set environment variables with whitespace os.environ['TOKEN'] = ' secret-token-with-spaces ' os.environ['MESSAGE'] = ' Hello World ' class Config(cabina.Config, cabina.Section): TOKEN_RAW: str = env.raw("TOKEN") TOKEN_CLEAN: str = env.str("TOKEN") MESSAGE_RAW: str = env.raw("MESSAGE") MESSAGE_CLEAN: str = env.str("MESSAGE") # Compare raw vs cleaned values print(repr(Config.TOKEN_RAW)) # Output: ' secret-token-with-spaces ' print(repr(Config.TOKEN_CLEAN)) # Output: 'secret-token-with-spaces' print(repr(Config.MESSAGE_RAW)) # Output: ' Hello World ' print(repr(Config.MESSAGE_CLEAN)) # Output: 'Hello World' ``` -------------------------------- ### Define Development and Test Configurations in Python Source: https://context7.com/tsv1/cabina/llms.txt Demonstrates how to extend base configurations for development and testing environments using Python classes. This pattern allows for environment-specific overrides of settings like DEBUG mode and database hostnames. ```python class ConfigDev(Config): class App(Config.App): DEBUG: bool = True class Database(Config.Database): HOST: str = "localhost" PORT: int = 5433 class ConfigTest(ConfigDev): class Database(ConfigDev.Database): HOST: str = "test-db.local" POOL_SIZE: int = 5 print(Config.App.DEBUG) # Output: False print(ConfigDev.App.DEBUG) # Output: True print(ConfigDev.Database.HOST) # Output: 'localhost' print(ConfigTest.Database.HOST) # Output: 'test-db.local' print(ConfigTest.Database.POOL_SIZE) # Output: 5 ``` -------------------------------- ### Root Section Configuration (Python) Source: https://github.com/tsv1/cabina/blob/main/README.md Demonstrates using cabina for simple, flat configurations by inheriting both `cabina.Config` and `cabina.Section`. It shows how to set environment variables and access them directly from the config class. ```python import cabina from cabina import env class Config(cabina.Config, cabina.Section): # Note the inheritance API_HOST = env.str("API_HOST") API_PORT = env.int("API_PORT") assert Config.API_HOST == "localhost" assert Config.API_PORT == 8080 ``` -------------------------------- ### Using Prefixes for Environment Variables in Cabina Source: https://github.com/tsv1/cabina/blob/main/README.md Illustrates how to use a prefix for all environment variables to prevent naming collisions. It shows setting up an `cabina.Environment` with a prefix and defining configuration classes that use shortened variable names, which are automatically prefixed. ```sh export APP_HOST=localhost export APP_PORT=8080 ``` ```python import cabina env = cabina.Environment(prefix="APP_") class Config(cabina.Config, cabina.Section): API_HOST = env.str("HOST") # 'APP_HOST' will be used API_PORT = env.int("PORT") # 'APP_PORT' will be used assert Config.API_HOST == "localhost" assert Config.API_PORT == 8080 ``` -------------------------------- ### Environment Variable Parsing with Default Values in Python Source: https://context7.com/tsv1/cabina/llms.txt Demonstrates how to handle missing environment variables gracefully in Python using Cabina by providing default values for optional configuration settings. This ensures the application can run even if some environment variables are not set. ```python import os import cabina from cabina import env # Only set some environment variables os.environ['APP_NAME'] = 'MyApplication' # APP_VERSION not set # MAX_WORKERS not set class Config(cabina.Config, cabina.Section): APP_NAME: str = env.str("APP_NAME", default="DefaultApp") APP_VERSION: str = env.str("APP_VERSION", default="1.0.0") MAX_WORKERS: int = env.int("MAX_WORKERS", default=4) ENABLE_METRICS: bool = env.bool("ENABLE_METRICS", default=False) # Defaults are used when environment variables don't exist print(Config.APP_NAME) # Output: 'MyApplication' print(Config.APP_VERSION) # Output: '1.0.0' (default used) print(Config.MAX_WORKERS) # Output: 4 (default used) print(Config.ENABLE_METRICS) # Output: False (default used) ``` -------------------------------- ### Basic Configuration with Environment Variables in Python Source: https://context7.com/tsv1/cabina/llms.txt Demonstrates how to define a basic configuration class in Python using Cabina, automatically loading and parsing environment variables with type safety and default values. It uses `env.str`, `env.int`, and `env.bool` for type-specific environment variable parsing. ```python import os import cabina from cabina import env # Set environment variables os.environ['API_HOST'] = 'api.example.com' os.environ['API_PORT'] = '8080' os.environ['DEBUG'] = 'true' # Define configuration class Config(cabina.Config, cabina.Section): API_HOST: str = env.str("API_HOST", default="localhost") API_PORT: int = env.int("API_PORT", default=3000) DEBUG: bool = env.bool("DEBUG", default=False) # Access configuration values print(Config.API_HOST) # Output: 'api.example.com' print(Config.API_PORT) # Output: 8080 print(Config.DEBUG) # Output: True # Dictionary-style access print(Config["API_HOST"]) # Output: 'api.example.com' ``` -------------------------------- ### Handle Missing and Invalid Environment Variables with Cabina Source: https://context7.com/tsv1/cabina/llms.txt Demonstrates error handling for environment variables using Cabina's `EnvKeyError` and `EnvParseError`. It contrasts eager evaluation (errors on definition) with lazy evaluation (errors on access) and shows how to prefetch to catch all errors at once. ```python import os import cabina from cabina import env, lazy_env from cabina.errors import EnvKeyError, EnvParseError, ConfigEnvError os.environ['VALID_PORT'] = '8080' os.environ['INVALID_PORT'] = 'not-a-number' # MISSING_VAR not set try: class ConfigEager(cabina.Config, cabina.Section): VALID_PORT: int = env.int("VALID_PORT") MISSING_VAR: str = env.str("MISSING_VAR") # Raises EnvKeyError except EnvKeyError as e: print(f"Missing environment variable: {e}") class ConfigLazy(cabina.Config, cabina.Section): VALID_PORT: int = lazy_env.int("VALID_PORT") INVALID_PORT: int = lazy_env.int("INVALID_PORT") MISSING_VAR: str = lazy_env.str("MISSING_VAR") print(ConfigLazy.VALID_PORT) # Output: 8080 try: ConfigLazy.prefetch() except ConfigEnvError as e: print(f"Configuration errors found:\n{e}") ``` -------------------------------- ### Hierarchical Configuration Sections in Python Source: https://context7.com/tsv1/cabina/llms.txt Illustrates how to create multi-level configuration structures in Python using Cabina with nested sections. This allows for organized management of complex configurations by grouping related settings. ```python import os import cabina from cabina import env os.environ['DB_HOST'] = 'postgres.local' os.environ['DB_PORT'] = '5432' os.environ['REDIS_HOST'] = 'redis.local' os.environ['REDIS_PORT'] = '6379' class Config(cabina.Config): class Database(cabina.Section): HOST: str = env.str("DB_HOST") PORT: int = env.int("DB_PORT") class Cache(cabina.Section): HOST: str = env.str("REDIS_HOST") PORT: int = env.int("REDIS_PORT") # Access nested configuration print(Config.Database.HOST) # Output: 'postgres.local' print(Config.Cache.PORT) # Output: 6379 # Dictionary-style nested access print(Config["Database"]["HOST"]) # Output: 'postgres.local' # Print entire configuration print(Config) # Output: # class : # class : # HOST = 'postgres.local' # PORT = 5432 # class : # HOST = 'redis.local' # PORT = 6379 ``` -------------------------------- ### Configuration Inheritance in Cabina Source: https://github.com/tsv1/cabina/blob/main/README.md Explains how to create a base configuration class and extend it for local or specialized environments. This allows for modular configuration management by overriding specific settings in derived classes. ```python import cabina class Config(cabina.Config, cabina.Section): DEBUG = False class Api(cabina.Section): API_HOST = "app.dev" API_PORT = 5000 class ConfigLocal(Config): DEBUG = True class Api(Config.Api): API_HOST = "localhost" assert ConfigLocal.DEBUG is True assert ConfigLocal.Api.API_HOST == "localhost" assert ConfigLocal.Api.API_PORT == 5000 ``` -------------------------------- ### Lazy Environment Variable Parsing with Cabina Source: https://github.com/tsv1/cabina/blob/main/README.md Demonstrates deferring the parsing of environment variables until their first access. This is useful for variables that might not exist at import time. It shows how to define configuration classes with lazy environment variables and highlights potential errors during prefetching. ```sh export DEBUG=yes export API_PORT=80a # Contains an invalid int "80a" ``` ```python import cabina from cabina import lazy_env class Config(cabina.Config, cabina.Section): DEBUG = lazy_env.bool("DEBUG") API_HOST = lazy_env.str("API_HOST") # Only fetched upon attribute access API_PORT = lazy_env.int("API_PORT") # Attempt to fetch all at once Config.prefetch() # Raises ConfigEnvError with: # - Config.API_HOST: 'API_HOST' does not exist # - Config.API_PORT: Failed to parse '80a' as int ``` -------------------------------- ### JSON Parser for Environment Variables (Python) Source: https://github.com/tsv1/cabina/blob/main/README.md Shows how to easily load JSON data from an environment variable using `json.loads` as a parser with `cabina.env`. This is useful for configuring complex settings. ```python import json import cabina from cabina import env class Config(cabina.Config, cabina.Section): IMAGE_SETTINGS = env("IMAGE_SETTINGS", parser=json.loads) assert Config.IMAGE_SETTINGS == { "AllowedContentTypes": ["image/png", "image/jpeg"] } ``` -------------------------------- ### Computed Configuration Values in Python Source: https://context7.com/tsv1/cabina/llms.txt Shows how to define dynamic configuration values in Python using Cabina's `@computed` decorator. These values are derived from other configuration attributes, enabling computed properties. ```python import os import cabina from cabina import computed, env os.environ['API_HOST'] = 'example.com' os.environ['API_PORT'] = '443' os.environ['API_PROTOCOL'] = 'https' class Config(cabina.Config, cabina.Section): API_HOST: str = env.str("API_HOST") API_PORT: int = env.int("API_PORT") API_PROTOCOL: str = env.str("API_PROTOCOL", default="http") @computed def API_URL(cls) -> str: return f"{cls.API_PROTOCOL}://{cls.API_HOST}:{cls.API_PORT}" @computed def API_ENDPOINT(cls) -> str: return f"{cls.API_URL}/api/v1" # Access computed values print(Config.API_URL) # Output: 'https://example.com:443' print(Config.API_ENDPOINT) # Output: 'https://example.com:443/api/v1' ``` -------------------------------- ### Raw Environment Variable Values (Python) Source: https://github.com/tsv1/cabina/blob/main/README.md Demonstrates how to retrieve the raw, unprocessed string value of an environment variable, including leading/trailing whitespace, using `env.raw()`. It contrasts this with `env.str()` which strips whitespace. ```python import cabina from cabina import env class Config(cabina.Config, cabina.Section): DEBUG_RAW = env.raw("DEBUG") # Same as env("DEBUG") without processing DEBUG_STR = env.str("DEBUG") # Strips whitespace assert Config.DEBUG_RAW == " yes" # The raw value includes whitespace assert Config.DEBUG_STR == "yes" # Whitespace is stripped ``` -------------------------------- ### Parse Boolean Environment Variables with Cabina Source: https://context7.com/tsv1/cabina/llms.txt Shows how to parse environment variables as booleans using `cabina.env.bool`. It supports flexible string representations like 'true', 'yes', '1', 'on' for `True` and 'false', 'no', '0' for `False`. ```python import os import cabina from cabina import env os.environ['FEATURE_A'] = 'true' os.environ['FEATURE_B'] = 'yes' os.environ['FEATURE_C'] = '1' os.environ['FEATURE_D'] = 'on' os.environ['FEATURE_E'] = 'false' os.environ['FEATURE_F'] = 'no' os.environ['FEATURE_G'] = '0' class Config(cabina.Config, cabina.Section): FEATURE_A: bool = env.bool("FEATURE_A") FEATURE_B: bool = env.bool("FEATURE_B") FEATURE_C: bool = env.bool("FEATURE_C") FEATURE_D: bool = env.bool("FEATURE_D") FEATURE_E: bool = env.bool("FEATURE_E") FEATURE_F: bool = env.bool("FEATURE_F") FEATURE_G: bool = env.bool("FEATURE_G") print(Config.FEATURE_A) # Output: True (from 'true') print(Config.FEATURE_B) # Output: True (from 'yes') print(Config.FEATURE_C) # Output: True (from '1') print(Config.FEATURE_D) # Output: True (from 'on') print(Config.FEATURE_E) # Output: False (from 'false') print(Config.FEATURE_F) # Output: False (from 'no') print(Config.FEATURE_G) # Output: False (from '0') ``` -------------------------------- ### Tuple Parsing with Custom Separators and Parsers (Python) Source: https://context7.com/tsv1/cabina/llms.txt Illustrates parsing delimited strings into tuples using `cabina.env.tuple`. This functionality supports custom separators (e.g., '|' or ',') and sub-parsers for individual tuple elements, such as `parse_int` or casting to `float`. This is useful for handling lists of values represented as single strings in environment variables. ```python import os import cabina from cabina import env from cabina.parsers import parse_int os.environ['ALLOWED_PORTS'] = '8080,8081,8082' os.environ['HOSTS'] = 'web1.local|web2.local|web3.local' os.environ['COORDINATES'] = '10.5,20.3,30.1' class Config(cabina.Config, cabina.Section): ALLOWED_PORTS: tuple = env.tuple("ALLOWED_PORTS", subparser=parse_int) HOSTS: tuple = env.tuple("HOSTS", separator="|") COORDINATES: tuple = env.tuple("COORDINATES", subparser=float) # Access tuple values print(Config.ALLOWED_PORTS) # Output: (8080, 8081, 8082) print(Config.HOSTS) # Output: ('web1.local', 'web2.local', 'web3.local') print(Config.COORDINATES) # Output: (10.5, 20.3, 30.1) print(Config.ALLOWED_PORTS[0]) # Output: 8080 ``` -------------------------------- ### Custom Parsers for Specialized Data Types (Python) Source: https://context7.com/tsv1/cabina/llms.txt Demonstrates how to use custom parsing functions with `cabina.env` to handle complex data types like JSON lists and dictionaries from environment variables. It defines functions `parse_json_list` and `parse_json_dict` and uses them within a `cabina.Config` class to parse string representations into Python objects. This allows for structured data directly from environment variables. ```python import os import json import cabina from cabina import env # Set complex environment variables os.environ['ALLOWED_ORIGINS'] = '["https://app.com", "https://api.com"]' os.environ['RATE_LIMITS'] = '{"default": 100, "premium": 1000}' os.environ['HTTP_TIMEOUT'] = '30.5' def parse_json_list(value: str) -> list: return json.loads(value) def parse_json_dict(value: str) -> dict: return json.loads(value) class Config(cabina.Config, cabina.Section): ALLOWED_ORIGINS: list = env("ALLOWED_ORIGINS", parser=parse_json_list) RATE_LIMITS: dict = env("RATE_LIMITS", parser=parse_json_dict) HTTP_TIMEOUT: float = env.float("HTTP_TIMEOUT") # Access parsed values print(Config.ALLOWED_ORIGINS) # Output: ['https://app.com', 'https://api.com'] print(Config.RATE_LIMITS) # Output: {'default': 100, 'premium': 1000} print(Config.HTTP_TIMEOUT) # Output: 30.5 print(Config.RATE_LIMITS['premium']) # Output: 1000 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.