How to use app.config.from_envvar? (Flask)
Categories:
Dynamic Flask Configuration with app.config.from_envvar

Learn how to securely manage Flask application configurations using environment variables with app.config.from_envvar
for flexible deployments.
Managing configuration in web applications is crucial for security, flexibility, and maintainability. Hardcoding sensitive information like API keys or database credentials is a major anti-pattern. Flask provides several ways to handle configuration, and app.config.from_envvar
offers a robust method to load configuration from a Python file specified by an environment variable. This approach allows you to easily switch configurations between development, testing, and production environments without modifying your codebase.
Why Use Environment Variables for Configuration?
Environment variables are a standard way to provide configuration to applications. They offer several key advantages:
- Security: Sensitive data (e.g., database passwords, API keys) can be kept out of version control systems. Instead, they are injected into the application's environment at runtime.
- Flexibility: You can easily change configurations for different deployment environments (development, staging, production) without altering the application code or rebuilding the Docker image.
- Portability: Applications can be deployed across various systems (local machine, CI/CD, cloud platforms) by simply setting the appropriate environment variables.
- Best Practice: It aligns with the Twelve-Factor App methodology, which advocates for strict separation of config from code.
flowchart TD A[Application Start] --> B{Check FLASK_CONFIG Environment Variable} B -- Variable Set --> C[Load Configuration File Path] C --> D["app.config.from_envvar('FLASK_CONFIG')"] D --> E[Configuration Loaded into Flask App] B -- Variable Not Set --> F[Default Configuration/Error] E --> G[Application Runs with Dynamic Config]
Flowchart illustrating how Flask loads configuration using from_envvar
.
Implementing app.config.from_envvar
To use app.config.from_envvar
, you'll typically follow these steps:
- Create Configuration Files: Define separate Python files for each environment (e.g.,
config_dev.py
,config_prod.py
). - Set Environment Variable: Before running your Flask application, set an environment variable (commonly
FLASK_CONFIG
) to point to the desired configuration file. - Load in Flask App: Use
app.config.from_envvar('FLASK_CONFIG')
in your Flask application's initialization code.
# config_dev.py
DEBUG = True
SECRET_KEY = 'dev-secret-key'
DATABASE_URI = 'sqlite:///dev.db'
# config_prod.py
DEBUG = False
SECRET_KEY = 'a-very-secret-production-key-that-should-be-randomly-generated'
DATABASE_URI = 'postgresql://user:password@host:port/prod_db'
Example configuration files for development and production environments.
# app.py
from flask import Flask
import os
app = Flask(__name__)
try:
app.config.from_envvar('FLASK_CONFIG')
except RuntimeError as e:
print(f"Error loading config: {e}")
print("Please set the 'FLASK_CONFIG' environment variable to point to a configuration file.")
# Fallback to a default config or raise an error
app.config.from_object('config.default_config') # Example fallback
@app.route('/')
def hello():
return f"Debug mode: {app.config['DEBUG']}, Database: {app.config['DATABASE_URI']}"
if __name__ == '__main__':
app.run()
Flask application loading configuration from an environment variable.
from_envvar
. If the environment variable is not set or points to a non-existent file, Flask will raise a RuntimeError
. Providing a fallback or clear error message improves robustness.Running the Application with Different Configurations
To run your application with different configurations, you simply set the FLASK_CONFIG
environment variable before executing your Flask app. Remember that the path specified in FLASK_CONFIG
should be an absolute path or relative to the directory from which the application is run.
# For development
export FLASK_CONFIG="/path/to/your/app/config_dev.py"
python app.py
# For production
export FLASK_CONFIG="/path/to/your/app/config_prod.py"
python app.py
Setting the FLASK_CONFIG
environment variable before running the Flask application.
SECRET_KEY
is a strong, randomly generated value and is not committed to version control. Environment variables are an excellent way to manage this.Alternative Configuration Loading Methods
While from_envvar
is powerful, Flask offers other configuration methods you might encounter or choose depending on your needs:
app.config.from_object('your_module.ConfigClass')
: Loads configuration from an object (class) within a Python module. This is often used for default configurations.app.config.from_pyfile('config.py')
: Loads configuration from a Python file directly, without requiring an environment variable.app.config.from_mapping(...)
: Loads configuration from a dictionary or keyword arguments.app.config.from_json('config.json')
: Loads configuration from a JSON file.
from_envvar
is particularly useful when you want to dynamically point to different configuration files based on the deployment environment, making it a flexible and secure choice for many projects.