Configuration & Environment
Relevant source files
The following files were used as context for generating this wiki page:
Starlette provides a robust system for managing application settings through environment variables and configuration files. This system is designed to handle type casting, default values, and sensitive data securely, ensuring that application behavior can be easily adjusted across different environments (development, staging, production) without code changes.
The core of this system lies in the Config and Environ classes, which facilitate a hierarchical lookup of settings. This configuration infrastructure is primarily used to initialize the Starlette application class, particularly for setting the debug mode and configuring various middleware.
Core Configuration Components
The configuration system is built around three primary entities: the Environ wrapper, the Config parser, and the Starlette application object which consumes these settings.
The Environ Class
The Environ class is a mutable mapping that wraps os.environ. Its primary purpose is to track which environment variables have been read. Once a variable is accessed via this class, it becomes immutable within the application context to prevent configuration drift during runtime.
This diagram shows the state management logic within the Environ class to ensure configuration consistency.
Sources: starlette/config.py:16-39, tests/test_config.py:92-113
The Config Class
The Config class provides the high-level API for retrieving settings. It supports reading from both a .env file and the system environment. It handles type casting (e.g., converting a string "true" to a boolean True) and provides support for default values.
| Feature | Description |
|---|---|
| Type Casting | Supports built-in types (int, bool, float) and custom callables. |
| Default Values | Allows specifying a fallback if a key is missing. |
| Prefixing | Supports an env_prefix to namespace configuration keys (e.g., APP_). |
| File Support | Can read key-value pairs from a specified .env file. |
Sources: starlette/config.py:48-115, tests/test_config.py:38-79
Configuration Data Flow
When a value is requested via Config.get(key), the system follows a specific resolution order.
The lookup hierarchy prioritizes live environment variables over file-based settings.
Sources: starlette/config.py:84-100
Type Casting Logic
The Config class includes specialized logic for boolean casting, recognizing strings like "true", "1", "false", and "0" as valid indicators. For other types, it attempts to use the provided cast callable.
def _perform_cast(self, key: str, value: Any, cast: Callable[[Any], Any] | None = None) -> Any:
if cast is None or value is None:
return value
elif cast is bool and isinstance(value, str):
mapping = {"true": True, "1": True, "false": False, "0": False}
value = value.lower()
if value not in mapping:
raise ValueError(f"Config '{key}' has value '{value}'. Not a valid bool.")
return mapping[value]
# ... standard casting follows
Sources: starlette/config.py:117-133
Application Integration
The most common use of the configuration system is within the Starlette application constructor. Key settings like debug influence how the application handles errors and telemetry.
Debug Mode and Error Handling
The debug boolean, typically loaded via config("DEBUG", cast=bool), determines if the application uses ServerErrorMiddleware in debug mode. When active, unhandled exceptions trigger a detailed HTML or plain text traceback instead of a generic "Internal Server Error".
| Setting | Type | Application Impact |
|---|---|---|
debug | bool | Enables detailed traceback responses and diagnostic info. |
lifespan | Lifespan | Configures startup and shutdown logic. |
middleware | Sequence | Defines the stack of processing layers for requests. |
Sources: starlette/applications.py:24-60, starlette/middleware/errors.py:155-188
Middleware Stack Configuration
The application builds its middleware stack based on these configurations. The ServerErrorMiddleware is always placed at the outermost layer to catch all exceptions, followed by user-defined middleware, and finally ExceptionMiddleware at the innermost layer.
Visual representation of the order in which middleware is initialized based on the application's configuration.
Sources: starlette/applications.py:62-81
Summary
Starlette's configuration system provides a secure and flexible way to manage environment-specific settings. By utilizing the Config class, developers can ensure type safety and consistent behavior across deployments. The integration of these settings into the Starlette application class allows for centralized control over critical features like debugging, error handling, and the middleware pipeline.