Environment Variables in Django
What Are Environment Variables?
Environment variables are key-value pairs stored outside a program that define settings or configurations the program can use. They help manage sensitive information (like API keys, database URLs) and allow apps to behave differently across development, testing, and production environments without changing the code.
Environment variables in Django
In Django, environment variables are used to manage sensitive settings like SECRET_KEY, DEBUG, and database credentials securely. Instead of hardcoding these values, Django reads them from the system environment, making the project safer and easier to configure across different environments.
Examples: Database credentials, secret keys, debug mode, API keys, allowed hosts.Using Environment Variables in Django
To manage environment variables in Django, we have several options available, ranging from using Python's built-in os.environ to dedicated libraries like python-decouple and django-environ for easier handling and better organization.
1. Using os (Standard Way):
os.environ is a built-in Python dictionary-like object used to access environment variables. It allows you to read system settings (e.g., database URLs, API keys) directly from your operating system. However, you need to manually handle type conversion and missing keys.
# settings.py
import os
SECRET_KEY = os.environ.get('SECRET_KEY', 'default_value')
DEBUG = os.environ.get('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')
DATABASE_URL = os.environ.get('DATABASE_URL')
2. Using python-decouple:
python-decouple is a Python library that simplifies managing environment variables by separating configuration from code. It allows you to load settings from .env files and provides easy type casting (e.g., converting strings to booleans, integers). It's cleaner and more organized than manually using os.environ.
# Install python-decouple to manage environment variables
pip install python-decouple
# .env file
DEBUG=True
SECRET_KEY=my-very-secret-key
ALLOWED_HOSTS=localhost,127.0.0.1
DATABASE_URL=postgres://user:password@localhost/dbname
# settings.py
from decouple import config, Csv
# Load environment variables
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
DATABASE_URL = config('DATABASE_URL')
3. Using django-environ:
django-environ is a library for managing Django settings with environment variables and .env files. It simplifies handling sensitive data securely by loading settings and automatically casting them to the correct data type. It works well in both Django and non-Django projects for managing configuration.
# Install django-environ for env variable management
pip install django-environ
# .env file
DEBUG=True
SECRET_KEY=my-secret-key
DATABASE_URL=postgres://user:password@localhost/dbname
RECAPTCHA_PUBLIC_KEY=your-public-key
RECAPTCHA_PRIVATE_KEY=your-private-key
# Read the variables from the .env file
# settings.py
import environ
import os
# Set up environment variables
env = environ.Env(
# Casting values with default fallback
DEBUG=(bool, False)
)
# Read variables from .env using BASE_DIR from Django settings
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# Django settings
DEBUG = env('DEBUG')
SECRET_KEY = env('SECRET_KEY')
DATABASE_URL = env('DATABASE_URL')
# Google reCAPTCHA keys
RECAPTCHA_PUBLIC_KEY = env('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = env('RECAPTCHA_PRIVATE_KEY')
Best Practices
Best practices for using environment variables include keeping sensitive information, such as keys and passwords, outside your codebase. This ensures better security and protects your credentials from being exposed.
These are the best practices you should follow:
- Always ignore .env in .gitignore to secure sensitive data.
- Add .env to .dockerignore if using Docker for added protection.
- Set default values carefully for critical settings like DEBUG and ALLOWED_HOSTS.
- Never leave DEBUG=True in production—always disable it for security.
- Use proper type casting for environment variables to avoid errors.
Important Note:
Forgetting to restart the server after updating .env credentials can cause the application to use outdated settings. Always restart the server to apply the latest changes to environment variables.
Exercise
- Fill in the Blanks:
- - Environment variables are __________ pairs stored outside a program.
- - Always ignore __________ in .gitignore to secure sensitive data.
- - To read environment variables using django-environ, call the __________ method.
- - To manage environment variables in a cleaner way, you can use the __________ library.
- - It's important to restart the __________ to apply the latest .env settings.