Learn / Frameworks / Django / Middleware, Signals and Settings

Django · Lesson 9 of 15

Middleware, Signals and Settings

The request pipeline, decoupling with signals and splitting settings.

  • Intermediate
  • 15 min read
  • 3 objectives

Before this lessonLesson 8: The ORM in Depth

What you will learn

  • Write middleware
  • Connect a signal
  • Split settings modules

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Every request passes through middleware on the way in and out. Signals let apps react to events (a user saved, a request finished) without importing each other.

A small middleware

# app/middleware.py
class RequestIdMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.request_id = request.headers.get("X-Request-Id", "-")
        response = self.get_response(request)
        response["X-Request-Id"] = request.request_id
        return response

Add the dotted path to MIDDLEWARE. Order matters: SecurityMiddleware and SessionMiddleware should stay near the top.

Signals

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

Register the module in AppConfig.ready() so the receiver is imported once.

Settings as a package

config/settings/
  __init__.py      # from .dev import *  (local default)
  base.py
  dev.py
  prod.py
# prod.py
from .base import *
DEBUG = False
ALLOWED_HOSTS = ["www.example.com"]
SECURE_SSL_REDIRECT = True
Up next · Lesson 10Testing Django AppsTestCase, the test client, fixtures and asserting on the database.