Skip to content

Chapter 17: Deployment

17.1 Production Environment Configuration

Settings Separation

Separate Django settings files for development, testing, and production environments:

python
# settings/__init__.py
import os

# Load different settings files based on environment variables
DJANGO_ENV = os.environ.get('DJANGO_ENV', 'development')

if DJANGO_ENV == 'production':
    from .production import *
elif DJANGO_ENV == 'staging':
    from .staging import *
elif DJANGO_ENV == 'testing':
    from .testing import *
else:
    from .development import *

# settings/base.py
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent.parent

# Security settings
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'your-secret-key-here')
DEBUG = False
ALLOWED_HOSTS = []

# Application configuration
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'accounts',
    # Other applications...
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myproject.wsgi.application'

# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

# Default primary key field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# settings/development.py
from .base import *

DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

# Development database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Development email backend
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Development logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'DEBUG',
    },
}

# settings/production.py
from .base import *
import os

DEBUG = False
ALLOWED_HOSTS = [
    'yourdomain.com',
    'www.yourdomain.com',
    os.environ.get('SERVER_IP', ''),
]

# Production database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('DB_NAME', 'myproject'),
        'USER': os.environ.get('DB_USER', 'myproject'),
        'PASSWORD': os.environ.get('DB_PASSWORD', ''),
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        'PORT': os.environ.get('DB_PORT', '5432'),
        'OPTIONS': {
            'charset': 'utf8mb4',
        },
    }
}

# Cache configuration
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379/1'),
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}

# Security settings
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_SECONDS = 31536000
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

# Email configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.environ.get('EMAIL_HOST', 'smtp.gmail.com')
EMAIL_PORT = int(os.environ.get('EMAIL_PORT', 587))
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')

# Static files storage
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = '/var/www/myproject/media/'

# Logging configuration
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': '/var/log/django/myproject.log',
            'formatter': 'verbose',
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
        },
    },
    'root': {
        'handlers': ['file'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'mail_admins'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

Environment Variables

Using environment variables to manage sensitive configurations:

python
# .env file example
"""
DJANGO_ENV=production
DJANGO_SECRET_KEY=your-very-long-secret-key-here
DEBUG=False

# Database configuration
DB_NAME=myproject
DB_USER=myproject
DB_PASSWORD=your-db-password
DB_HOST=localhost
DB_PORT=5432

# Redis configuration
REDIS_URL=redis://127.0.0.1:6379/1

# Email configuration
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=your-email@gmail.com
EMAIL_HOST_PASSWORD=your-app-password

# Server configuration
SERVER_IP=your-server-ip
"""

# env.py
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

def get_env_variable(var_name, default=None, required=False):
    """Get environment variable"""
    value = os.environ.get(var_name, default)
    
    if required and value is None:
        raise ValueError(f"Environment variable {var_name} is required")
    
    return value

def get_bool_env_variable(var_name, default=False):
    """Get boolean environment variable"""
    value = os.environ.get(var_name, str(default)).lower()
    return value in ('true', '1', 'yes', 'on')

def get_int_env_variable(var_name, default=0):
    """Get integer environment variable"""
    try:
        return int(os.environ.get(var_name, default))
    except ValueError:
        return default

# Use in settings
from .env import get_env_variable, get_bool_env_variable, get_int_env_variable

SECRET_KEY = get_env_variable('DJANGO_SECRET_KEY', required=True)
DEBUG = get_bool_env_variable('DEBUG', False)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': get_env_variable('DB_NAME', 'myproject'),
        'USER': get_env_variable('DB_USER', 'myproject'),
        'PASSWORD': get_env_variable('DB_PASSWORD', required=True),
        'HOST': get_env_variable('DB_HOST', 'localhost'),
        'PORT': get_env_variable('DB_PORT', '5432'),
    }
}

# Configuration management class
class Config:
    """Configuration management class"""
    
    @classmethod
    def get_database_config(cls):
        """Get database configuration"""
        return {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': get_env_variable('DB_NAME', 'myproject'),
            'USER': get_env_variable('DB_USER', 'myproject'),
            'PASSWORD': get_env_variable('DB_PASSWORD', required=True),
            'HOST': get_env_variable('DB_HOST', 'localhost'),
            'PORT': get_env_variable('DB_PORT', '5432'),
        }
    
    @classmethod
    def get_redis_config(cls):
        """Get Redis configuration"""
        return {
            'BACKEND': 'django_redis.cache.RedisCache',
            'LOCATION': get_env_variable('REDIS_URL', 'redis://127.0.0.1:6379/1'),
            'OPTIONS': {
                'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            }
        }
    
    @classmethod
    def get_email_config(cls):
        """Get email configuration"""
        return {
            'EMAIL_BACKEND': 'django.core.mail.backends.smtp.EmailBackend',
            'EMAIL_HOST': get_env_variable('EMAIL_HOST', 'smtp.gmail.com'),
            'EMAIL_PORT': get_int_env_variable('EMAIL_PORT', 587),
            'EMAIL_USE_TLS': get_bool_env_variable('EMAIL_USE_TLS', True),
            'EMAIL_HOST_USER': get_env_variable('EMAIL_HOST_USER', required=True),
            'EMAIL_HOST_PASSWORD': get_env_variable('EMAIL_HOST_PASSWORD', required=True),
        }

Logging Configuration

Detailed logging configuration to monitor production environment:

python
# logging_config.py
import os
from .env import get_env_variable

# Log directory
LOG_DIR = get_env_variable('LOG_DIR', '/var/log/django')

# Ensure log directory exists
os.makedirs(LOG_DIR, exist_ok=True)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {asctime} {message}',
            'style': '{',
        },
        'django.server': {
            '()': 'django.utils.log.ServerFormatter',
            'format': '[{server_time}] {message}',
            'style': '{',
        }
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'django.server': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'django.server',
        },
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_DIR, 'django.log'),
            'maxBytes': 1024*1024*15,  # 15MB
            'backupCount': 10,
            'formatter': 'verbose',
        },
        'error_file': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_DIR, 'django_error.log'),
            'maxBytes': 1024*1024*15,  # 15MB
            'backupCount': 10,
            'formatter': 'verbose',
        },
        'security_file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_DIR, 'security.log'),
            'maxBytes': 1024*1024*15,  # 15MB
            'backupCount': 10,
            'formatter': 'verbose',
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        }
    },
    'root': {
        'handlers': ['console', 'file'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'error_file', 'mail_admins'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.server': {
            'handlers': ['django.server'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.security': {
            'handlers': ['security_file', 'mail_admins'],
            'level': 'INFO',
            'propagate': False,
        },
        'myproject': {
            'handlers': ['file', 'error_file'],
            'level': 'INFO',
            'propagate': False,
        },
    }
}

# Custom logger
import logging

# Create application-specific loggers
logger = logging.getLogger('myproject')
security_logger = logging.getLogger('django.security')
performance_logger = logging.getLogger('myproject.performance')

# Use logging in views
from django.shortcuts import render
import time

def article_detail(request, slug):
    start_time = time.time()
    
    try:
        article = get_object_or_404(Article, slug=slug)
        
        # Record performance log
        duration = time.time() - start_time
        performance_logger.info(
            f"Article detail view for {slug} took {duration:.3f} seconds"
        )
        
        return render(request, 'blog/article_detail.html', {'article': article})
    
    except Exception as e:
        # Record error log
        logger.error(
            f"Error in article_detail view for {slug}: {str(e)}",
            exc_info=True,
            extra={
                'request': request,
                'user_id': request.user.id if request.user.is_authenticated else None,
            }
        )
        raise

# Add request logging in middleware
class RequestLoggingMiddleware:
    """Request logging middleware"""
    
    def __init__(self, get_response):
        self.get_response = get_response
        self.logger = logging.getLogger('myproject.requests')
    
    def __call__(self, request):
        start_time = time.time()
        
        response = self.get_response(request)
        
        # Record request log
        duration = time.time() - start_time
        self.logger.info(
            f"{request.method} {request.path} - "
            f"Status: {response.status_code} - "
            f"Duration: {duration:.3f}s - "
            f"User: {getattr(request.user, 'username', 'Anonymous')}"
        )
        
        return response

Security Settings

Security configuration for production environment:

python
# security.py
from .env import get_bool_env_variable, get_env_variable

# Basic security settings
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_REDIRECT = get_bool_env_variable('SECURE_SSL_REDIRECT', True)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Cookie security settings
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = 1209600  # 2 weeks
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True

# Authentication security settings
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 8,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# File upload security
FILE_UPLOAD_MAX_MEMORY_SIZE = 5242880  # 5MB
DATA_UPLOAD_MAX_MEMORY_SIZE = 5242880  # 5MB
DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000

# Limit request frequency
# Can use django-ratelimit or other third-party packages

# CORS settings (if needed)
# Install: pip install django-cors-headers

# CORS_ALLOWED_ORIGINS = [
#     "https://yourdomain.com",
#     "https://www.yourdomain.com",
# ]

# CORS_ALLOW_CREDENTIALS = True

# Content Security Policy
# Can use django-csp package

# CSP_DEFAULT_SRC = ("'self'",)
# CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "https://cdn.example.com")
# CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", "https://cdn.example.com")
# CSP_IMG_SRC = ("'self'", "data:", "https://cdn.example.com")

# Security middleware
SECURITY_MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    # 'csp.middleware.CSPMiddleware',  # If using CSP
]

# Custom security checks
from django.core.exceptions import SuspiciousOperation

class SecurityMiddleware:
    """Custom security middleware"""
    
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        # Check user agent
        user_agent = request.META.get('HTTP_USER_AGENT', '')
        suspicious_agents = ['malicious-bot', 'scanner']
        
        if any(agent in user_agent.lower() for agent in suspicious_agents):
            raise SuspiciousOperation("Suspicious user agent detected")
        
        # Check request frequency (simplified example)
        client_ip = self.get_client_ip(request)
        # Actual rate limiting logic should be implemented here
        
        response = self.get_response(request)
        return response
    
    def get_client_ip(self, request):
        """Get client IP"""
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

# Security view decorators
from django.contrib.auth.decorators import user_passes_test
from django.core.exceptions import PermissionDenied

def require_ajax(view_func):
    """Decorator requiring AJAX request"""
    def wrapper(request, *args, **kwargs):
        if not request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            raise PermissionDenied("AJAX request required")
        return view_func(request, *args, **kwargs)
    return wrapper

def require_https(view_func):
    """Decorator requiring HTTPS request"""
    def wrapper(request, *args, **kwargs):
        if not request.is_secure() and not settings.DEBUG:
            raise PermissionDenied("HTTPS required")
        return view_func(request, *args, **kwargs)
    return wrapper

Through these production environment configurations, you can ensure the security, stability, and maintainability of Django applications in production environments.

Summary

Core points of Django production environment configuration:

  1. ✅ Separate settings files for different environments to ensure configuration flexibility
  2. ✅ Use environment variables to manage sensitive configuration information
  3. ✅ Configure detailed logging systems for problem troubleshooting
  4. ✅ Implement comprehensive security settings to protect application security
  5. ✅ Optimize database, cache, and static file configurations

Proper production environment configuration is the foundation for stable application operation.

Next Article

We will learn about specific deployment solutions.

17.2 Deployment Solutions →

Directory

Return to Course Directory

Released under the [BY-NC-ND License](https://creativecommons.org/licenses/by-nc-nd/4.0/deed.en).