Archive for January, 2011

Anthony Lenton

Debug Django with the Werkzeug debugger

The great Django command-extensions app gives you an easy way to integrate the Werkzeug debugger into your Django site.

For if you’ve never used this debugger before, imagine the regular Django technical details debugging page, with all same super useful information — environment variables, sql queries, and a full traceback with even the local variables and a bit of code context for each frame.
Now imagine you could have a pdb prompt running within each frame of the traceback, actually running interactively via ajax within the frames that you see.  That’s the kind of raw power Werkzeug gives you.

A big disclaimer though: this is not for running on production sites.  You’ll be giving anybody that happens to stumble upon a failure page an interactive (unrestricted) python terminal running with the web server’s permissions on your box.

So, this is just what out the box django-command-extension’s runserver_plus gives you.  With a bit of tweaking, here are a couple of other neat things you can do:

Make your server multithreaded

There are times when you need a multithreaded server in your development environment.  I’ve seen arguments about this being a smell for bad design, so here ar two reasonable scenarios I’ve come across:

  • Developing a web API, you might have a view that provides a test consumer for the API, not intended to be available on production.  The test consumer view will make a (blocking) call out to the API that’s provided by the same server, hanging everything if you don’t have multithreadedness.
  • Or, in larger systems where you have more than one application server, you might have a view or two that do a bit of communication between servers (to see if everything’s ok, to provide a neat server status screen), that you’ll need to test calling out to the same server during development.

For whatever reason it may be, if you need to enable threading, you can just set threaded=True when you call Werkzeug’s run_simple function:

runserver_threaded.py

runserver_threaded.py

Debug your whole wsgi app instead of just Django

If you’re running Django as part of a larger wsgi stack (a non-Django web api, or some authentication wsgi middleware), you probably would love to be able to run the whole stack in your development server, and even have those same great debugging features available for everything, not only Django.
You can do this by modifying the wsgi app that Werkzeug debugs:

myrunserver_plus.py

myrunserver_plus.py

It’s something with raw power that keeps getting better the more you look…