4th Aug, 2010

Django: From request to response

In an ongoing effort to learn a bit more about Django I thought I’d show how a request / response is structured*. This is taken from the point of view of a WSGI request, mod_python and runserver are slightly different but only until request_class is set. I’ve left out any mention of models and the ORM and the actual parsing of templates as it’s a bit out of scope for this post.

Overview

Ok, so running through the whole process we start off in core/handlers, then move off into middleware, back to core/urlresolvers and then into your view code.

  • handlers live in core/handlers
  • WSGI script sets paths and environment vars (DJANGO_SETTINGS_MODULE)
  • WSGI script loads WSGIHandler
  • Handler sets request_class (WSGIRequest - inherits BaseHandler)
  • Handler get_response:
    • Loads middleware lists
    • Calls request middlewares
    • Gets URLs and parses to find view function [1]
    • Calls view middlewares
    • Calls view function [2] and gets response back
    • Calls error middlewares if anything went wrong
    • Returns response or raises appropriate errors or 404

[1] URLs

Core/urlresolvers.py does all of the work; it’s a regex matching engine (could it have been anything else?).

  • As Django tries to match a URL it stores the rule in a list used in the 404 debug page
  • Once a url is matched, a view name, and a dict with any other info
  • If nothing is found a 404 is raised

[2] Views

There are a hundred ways to skin this particular animal, and you should have done this quite a lot already for the rest of this article to make any sense. Anyway, here’s a general overview of the process:

  • First the view does whatever it needs to achieve (process form, load, save data etc.)
  • View constructs a context dictionary
  • A Template is loaded via loader.get_template(‘template_path’’)
  • Some sort of HttpResponse is called with the results of the template rendered against the context dictionary and a mime type

This is all based on a fairly quick code reading so bits of it could be inaccurate

Related: django

Comments are now closed.

Comments have been closed for this post.

Comments

Projects