Environment Configuration
Your application behaves differently depending on where it runs. Locally, you might use a SQLite file for your database. In production, you need a real PostgreSQL server. Environment variables let you change this configuration without changing your code.
Why Configuration Matters
Hardcoding values like database URLs or API keys creates problems:
- You can't run the same code in different environments
- Secrets end up in your code repository
- Changing configuration requires code changes and redeployment
Instead, your code reads configuration from the environment, and each environment provides its own values.
Environment Variables in Practice
Environment variables are key-value pairs available to your running application. Your code reads them at startup:
import os
DATABASE_URL = os.environ.get('DATABASE_URL', 'sqlite:///local.db')
DEBUG = os.environ.get('DEBUG', 'True').lower() == 'true'
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-key-change-in-production')
The second argument to get() provides a default value for local development. This means your app works out of the box locally but uses proper values in production.
Using .env Files Locally
Typing environment variables every time you start your app gets tedious. A .env file stores them for local development:
DATABASE_URL=sqlite:///local.db
DEBUG=True
SECRET_KEY=my-local-dev-key
Libraries like python-dotenv load this file automatically. Add .env to your .gitignore — it should never be committed to version control.
Different Environments
Most applications have at least two environments:
Development (your laptop): Debug mode on, local database, relaxed security settings.
Production (live server): Debug mode off, real database, strict security, real secrets.
Some teams add a staging environment that mirrors production for testing before release.
Handling Secrets
Secrets — API keys, database passwords, encryption keys — need special care:
- Never commit them to Git
- Never log them
- Use different values for each environment
- Rotate them periodically
For production, use your hosting platform's secrets management. Railway, Render, and similar platforms have built-in ways to set environment variables securely.
For more complex needs, dedicated tools like AWS Secrets Manager or HashiCorp Vault provide additional security features.
Configuration Checklist
Before deploying, verify:
- No hardcoded secrets in code
-
.envis in.gitignore - Production environment variables are set
- Debug mode is off in production
- Database URL points to production database