Охватываемые темы: Why use environment variables, python-dotenv, django-environ (alternative), .gitignore.
Why use environment variables
- Secrets (SECRET_KEY, passwords) never end up in git
- Different settings for dev/prod without changing code
python-dotenv
pip install python-dotenv
# .env (in the project root, do NOT commit)
SECRET_KEY=django-insecure-abc123
DEBUG=True
DATABASE_URL=sqlite:///db.sqlite3
ALLOWED_HOSTS=localhost,127.0.0.1
# settings.py
from pathlib import Path
from dotenv import load_dotenv
import os
load_dotenv()
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = os.environ.get('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')
django-environ (alternative)
pip install django-environ
import environ
env = environ.Env()
environ.Env.read_env('.env')
DEBUG = env.bool('DEBUG', default=False)
SECRET_KEY = env.str('SECRET_KEY')
DATABASES = {'default': env.db('DATABASE_URL')}
.gitignore
.env
*.env
.env.local
.env.example (template for the team)
# .env.example — commit this to the repository
SECRET_KEY=your-secret-key-here
DEBUG=True
DATABASE_URL=sqlite:///db.sqlite3
ALLOWED_HOSTS=localhost
Production check
# Railway, Heroku, Docker: variables are set on the platform
# No .env file needed on the server
export SECRET_KEY="production-secret"
export DEBUG="False"
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!