March 4, 2006

Snakes on the Web [Django How-to]

The third speaker for my session as chair was Jacob Kaplan-Moss, one of the two primary developers of Django. He took as his example a sudoku solver, explaining that his company had been paying $180 per week for a third-party service to provide sudoku puzzles, so there was a potential saving here of $8,000 per annum.

The Django application stack is Model/URL/View/Template. Jacob explained he was going to walk us through the whole stack in developing the application. Many people are surprised to see the URL in there, but hey, that's how the app interfaces with the real world.

All models inherit from django.core.meta.model, and you can easily give your application an online production-ready admin interface by creating a META class with an admin class attribute. The model describes much more than just the database structure. A class can have a validator list, in which case all validators must return true.

The applications used Eppstein's well-known PADS algorithm to generate sudoku puzzles. This creates a puzzle and saves it in a database. The database layer is explicitly called, nothing ever happens without a specific API call, as opposed to other object-relational mappers that perform database I/O autonomically.

URL patterns are established to determine which URL calls what piece of view functionality. When a request is submitted get_validation_errors() will return a dict of errors. Callable returns render_to_response(template, context).

The Django templating language is relatively simple, and this was a deliberate design choice. It was primarly so that technically unsophisticated users in the newspaper production environment would find it straightforward and intuitive.

Jacob continued the development of his example by adding a further model for solving puzzles, walking through the solution provided by the PADS algorithm.

Django applications area pretty much pluggable, so if you have Django running all you need to do is download the code, add it to sys.path, add sudoku to INSTALLED_APPS, include the URLs for sudoku somewhere in the mapping (an inclusion mechanism allows the inclusion of a bunch of URLs with a single pattern match, and ths feature extends to multiple levels). Finally use django-admin to install sudoku.

Tadaa! Once again an effective demonstration of a Python-based web technology that people should be adopting in droves.

No comments: