Project Deployment
Environment Variables
Manage configuration
Environment Variables
Environment variables are a way to store configuration outside of your code. This is essential for keeping sensitive information secure and making your application configurable across different environments.
Why Use Environment Variables?
- Security: Keep secrets out of your code
- Flexibility: Different settings for dev/staging/production
- Best Practice: Follows the 12-factor app methodology
Create .env File
Create a .env file in your project root:
# Database
DATABASE_URL=postgresql://user:password@localhost/dbname
# Django
SECRET_KEY=your-secret-key-here
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1
# API Keys
API_KEY=your-api-key-here
# Email
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your-password
Install python-dotenv
pip install python-dotenv
Load Environment Variables
In your Python code:
from dotenv import load_dotenv
import os
# Load .env file
load_dotenv()
# Access variables
database_url = os.getenv('DATABASE_URL')
secret_key = os.getenv('SECRET_KEY')
debug = os.getenv('DEBUG', 'False').lower() == 'true'
Django Settings Example
import os
from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = os.getenv('DEBUG', 'False').lower() == 'true'
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '').split(',')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DB_NAME'),
'USER': os.getenv('DB_USER'),
'PASSWORD': os.getenv('DB_PASSWORD'),
'HOST': os.getenv('DB_HOST', 'localhost'),
'PORT': os.getenv('DB_PORT', '5432'),
}
}
Important Notes
- Never commit
.envfiles to Git - Add
.envto.gitignore - Use different
.envfiles for different environments - Document required environment variables in README
Warning: Never expose your .env file or commit it to version control. It contains sensitive information!