⚙️ Environment Variables Configuration
Template for configuring your application settings
What Are Environment Variables?
Environment variables are settings that change depending on where the application runs.
Local Development:
FLASK_ENV=development
Production Server:
FLASK_ENV=production
Same code, different settings.
Why Use Environment Variables?
Without Environment Variables (Bad)
# In code (NEVER DO THIS!)
SECRET_KEY = "my-super-secret-key-12345"
DATABASE_URL = "postgresql://user:password@localhost/mydb"
DEBUG_MODE = True
Problems: - Secrets are visible in code - Can't change settings without editing code - Secrets get saved to git history - Everyone can see passwords
With Environment Variables (Good)
# In shell or platform config (DO THIS)
export SECRET_KEY="my-super-secret-key-12345"
export DATABASE_URL="postgresql://user:password@localhost/mydb"
export FLASK_ENV="production"
# In code (secure)
import os
SECRET_KEY = os.environ.get('SECRET_KEY')
DATABASE_URL = os.environ.get('DATABASE_URL')
FLASK_ENV = os.environ.get('FLASK_ENV', 'development')
Benefits: - Secrets are kept separate from code - Easy to change settings - Secrets are not in git history - Different settings per environment
Setting Environment Variables
Method 1: Command Line (Temporary)
# Set for one command
export FLASK_ENV=development
python run_v2.py
# Or in one line
FLASK_ENV=development python run_v2.py
# On Windows PowerShell
$env:FLASK_ENV="development"
python run_v2.py
How long it lasts: Until you close the terminal
Method 2: .env File (Local Development)
Create a file called .env in your project root:
# .env file
FLASK_ENV=development
FLASK_DEBUG=1
DATABASE_PATH=./core_v2/db_v2/app.db
SECRET_KEY=dev-key-not-for-production
PORT=5000
TIMEZONE=UTC
Then load it:
# In Python code or shell config
from dotenv import load_dotenv
load_dotenv()
How long it lasts: As long as your application runs
Method 3: Platform Dashboard (Production)
Most platforms (DigitalOcean, Heroku, AWS) have a dashboard:
Settings → Environment Variables
FLASK_ENV: production
SECRET_KEY: [your-production-key]
DATABASE_URL: [your-database-url]
How long it lasts: Until you change it
Method 4: Configuration Files (Advanced)
For complex setups, use configuration files:
# config.py
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-key'
FLASK_ENV = os.environ.get('FLASK_ENV', 'development')
class DevelopmentConfig(Config):
FLASK_DEBUG = True
DATABASE_URL = 'sqlite:///dev.db'
class ProductionConfig(Config):
FLASK_DEBUG = False
DATABASE_URL = os.environ.get('DATABASE_URL')
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
Common Environment Variables
Application Settings
| Variable | Example | Meaning |
|---|---|---|
| FLASK_ENV | development | Environment: development or production |
| FLASK_DEBUG | 1 | Debug mode: 1 (on) or 0 (off) |
| PORT | 5000 | Which port to run on |
| HOST | 0.0.0.0 | Which address to listen on |
Database Settings
| Variable | Example | Meaning |
|---|---|---|
| DATABASE_PATH | ./app.db | Path to SQLite file |
| DATABASE_URL | postgresql://user:pass@host/db | Database connection string |
| DATABASE_POOL_SIZE | 10 | Connection pool size |
Security Settings
| Variable | Example | Meaning |
|---|---|---|
| SECRET_KEY | your-random-key | Session encryption key |
| API_KEY | your-api-key | API authentication key |
| JWT_SECRET | your-jwt-secret | JWT signing key |
Application Settings
| Variable | Example | Meaning |
|---|---|---|
| TIMEZONE | UTC | Default timezone |
| LANGUAGE | en | Default language |
| MAX_RECORDS_PER_PAGE | 25 | Pagination size |
| SESSION_TIMEOUT | 3600 | Session timeout in seconds |
Logging & Monitoring
| Variable | Example | Meaning |
|---|---|---|
| LOG_LEVEL | INFO | Logging level: DEBUG, INFO, WARNING, ERROR |
| LOG_FILE | ./app.log | Where to write logs |
| SENTRY_DSN | https://... | Error tracking service |
Configuration Templates
Local Development (.env)
# Flask Configuration
FLASK_ENV=development
FLASK_DEBUG=1
PORT=5000
HOST=localhost
# Database
DATABASE_PATH=./core_v2/db_v2/app.db
# Security
SECRET_KEY=dev-key-change-in-production
# Logging
LOG_LEVEL=DEBUG
Production (via Platform Dashboard)
FLASK_ENV=production
FLASK_DEBUG=0
PORT=8080
HOST=0.0.0.0
DATABASE_URL=postgresql://user:secure_password@db.example.com:5432/myapp
SECRET_KEY=[generate-random-key-here]
LOG_LEVEL=INFO
SENTRY_DSN=[sentry-error-tracking-url]
Testing (.env.test)
FLASK_ENV=testing
FLASK_DEBUG=1
DATABASE_PATH=./test.db
DATABASE_RESET=true
SECRET_KEY=test-key-not-secure
Reading Environment Variables in Code
Python
import os
# Get with default value
env = os.environ.get('FLASK_ENV', 'development')
port = int(os.environ.get('PORT', 5000))
# Get without default (will be None if not set)
secret = os.environ.get('SECRET_KEY')
# Require environment variable (error if missing)
api_key = os.environ['API_KEY'] # Raises KeyError if not set
Flask
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['DATABASE_URL'] = os.environ.get('DATABASE_URL')
Generating Secure Keys
Secret Key (For Sessions)
# Python
python -c "import secrets; print(secrets.token_hex(32))"
# Result: 7f8c9d2e4a1b5c6f9e2d3a4b5c6f7e8d9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c
# Use this as SECRET_KEY
API Keys
# Generate random API key
python -c "import uuid; print(str(uuid.uuid4()))"
# Result: a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d
Security Best Practices
✅ DO - Store secrets in environment variables - Generate strong, random keys - Use different keys for each environment - Rotate keys regularly - Document which variables are required - Never commit .env files to git
❌ DON'T - Put secrets in code - Use simple/easy-to-guess values - Reuse keys across environments - Commit .env files - Share keys via email - Log sensitive values
.gitignore for Secrets
Make sure .env files are not committed:
# .gitignore
.env
.env.local
.env.*.local
__pycache__/
*.pyc
venv/
Checking Current Configuration
View Set Variables
# See all environment variables
env
# See specific variable
echo $FLASK_ENV # Mac/Linux
echo %FLASK_ENV% # Windows
# Python
import os
print(os.environ.get('FLASK_ENV'))
Verify Configuration
# In your application
@app.route('/config')
def config():
return {
'FLASK_ENV': app.config.get('FLASK_ENV'),
'DEBUG': app.config.get('DEBUG'),
'DATABASE': 'configured' if app.config.get('DATABASE_URL') else 'missing'
}
Troubleshooting
"Environment variable not found"
Meaning: Variable isn't set
Solution:
# Set it first
export VARIABLE_NAME="value"
# Then run app
python run_v2.py
"Connection refused" (Database)
Meaning: DATABASE_URL is wrong or database isn't running
Solution:
# Check DATABASE_URL
echo $DATABASE_URL
# Verify database is running
# (platform/server specific)
"Module not found" in Production
Meaning: requirements.txt is incomplete
Solution:
# List all installed packages
pip freeze > requirements.txt
# Commit and deploy
Next Steps
- Set up your local .env file
- Configure environment variables on your deployment platform
- Generate secure keys for production
Key Takeaway: Environment variables keep secrets safe and let you use different settings for different environments without changing code.