In this article, we explore how to externalize your application’s configuration to support different environments such as production, staging, and development. In our initial Python example, configuration values like the Redis host and port are hard-coded. This approach leads to issues, as each environment may require distinct settings, making it error-prone and inflexible.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
By moving configuration values out of the application code, you can manage settings dynamically and securely across different environments.
Hard-Coded Configuration: The Problem
Consider the following Python snippet, which uses fixed values for connecting to a Redis instance:Using Environment Variables for Configuration
To separate configuration from core application logic and secure sensitive details, store your environment-specific settings in a dedicated file, typically named.env. With the “.env” file, Python libraries can automatically load environment variables that can be accessed directly in your code.
This approach aligns with the 12 Factor App methodology, which emphasizes storing configuration in the environment. As a result, you can seamlessly transition between testing, staging, and production setups without making changes to the core code.
Example .env File
Below is an example of how your.env file might look:
-
Development Environment:
-
Staging Environment:
-
Production Environment:
Using environment variables to manage configuration ensures that you can safely open source your project without exposing sensitive details. This setup also facilitates smoother deployments across various environments.