All posts
Article · 1 min ·

Django: The Request-Response Cycle

When you type google.com and hit Enter, what actually happens?

The Journey

  1. Browser: Resolves DNS to an IP.
  2. Nginx: Receives the request on port 80/443. It acts as a Reverse Proxy.
  3. Gunicorn: Nginx passes the request to Gunicorn (WSGI Server) via a Unix Socket.
  4. Django WSGI: Gunicorn calls Django's application callable.
  5. Middleware: The request flows through layers (Security, Session, CSRF).
  6. URL Dispatcher: Django looks at urls.py.
  7. View: The logic runs. Database is queried.
  8. Template: HTML is rendered.

Middleware: The Onion

Think of Django as an onion. The request has to go through all layers to reach the center (the View), and the response goes back out through them.

# Custom Middleware Check
def simple_middleware(get_response):
    def middleware(request):
        # Code executed BEFORE the view
        print("Request coming in!")

        response = get_response(request)

        # Code executed AFTER the view
        print("Response going out!")
        return response
    return middleware

Conclusion

Understanding this cycle is crucial for debugging. If a request never reaches your View, it's likely stuck in Middleware or blocked by Nginx.

Related posts