Django HTTP Request-Response Lifecycle
This sequence diagram traces the lifecycle of an HTTP request in Django, from the moment it enters the BaseHandler to the final HttpResponse sent back to the client.
The process begins with BaseHandler.get_response, which triggers the MiddlewareChain. The middleware stack processes the request before passing it to BaseHandler._get_response. Inside this method, the URLResolver matches the request path to a View (callback).
Before the view is executed, process_view middleware hooks are called. If they don't return a response, the view is invoked. If the view returns a TemplateResponse, process_template_response middleware hooks are applied before the Template engine renders the final content. Finally, the response travels back through the middleware stack for post-processing before being returned to the client.
Key Architectural Findings:
- BaseHandler.load_middleware builds a recursive chain of middleware callables, with _get_response as the innermost handler.
- URLResolver.resolve is responsible for mapping the request's path_info to a view function and extracting URL parameters.
- Middleware can implement specific hooks like process_view and process_template_response which are called by BaseHandler at precise points in the lifecycle.
- TemplateResponse objects defer rendering until the render() method is explicitly called, allowing middleware to modify the context or template before final output.
- The entire chain is wrapped in convert_exception_to_response to ensure that even unhandled exceptions result in a valid HttpResponse (e.g., a 500 error page).