Environment Variables & Secrets
Environment Variables & Secrets
Hardcoding sensitive credentials—such as database passwords, Stripe API keys, AWS secret tokens, and Django's SECRET_KEY—directly into source code files is one of the most severe security vulnerabilities in software engineering. If source code is pushed to public repositories or shared across teams, exposed credentials allow attackers to compromise production systems. Professional Django architectures use Twelve-Factor App Environment Configuration.
1. The Twelve-Factor Configuration Principle
A codebase should be completely decoupled from environment credentials. The exact same container image or git commit should run in:
- Local Development: Reading local SQLite and mock API keys.
- Staging: Reading staging PostgreSQL and sandbox payment gateways.
- Production: Reading production RDS clusters and live payment credentials.
2. Managing Environments with python-dotenv
In local development, store secrets in a .env file at the root of your project:
3. Integrating .env in settings.py
Use python-dotenv or django-environ:
4. Git Hygiene: .gitignore and .env.example
To ensure teammates know which environment variables are required without exposing secrets, commit a template .env.example:
And guarantee .env is ignored in .gitignore:
Practice Quiz
Full Web Application
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Static & Media Files | Full Web Application |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.