I don’t like the dispatching system in turbogears

I wanted to translate a(1).b(2)into the TurboGears URL /a/1/b/2. A browser making a request for /a/1/b/2 would trigger that code.

This page explains how to do it. You build a single default method that catches everything and then does introspection to figure out where to send the request.

It works fine, but it isn’t nearly as obvious or concise as the regular-expression approach I’ve seen in rails and Django.

Using dictionaries rather than complex if-elif-else clauses

Lately, I’ve been using dictionaries as a dispatching mechanism. It seems especially elegant when I face some fairly elaborate switching logic.

For example, instead of:
if a == 1 and b == 1:
log("everything worked!")
commit()


elif a == 1 and b == 0:
log("a good, b bad")
report_that_b_failed()


else:
log("a failed")
report_that_a_failed()

Do this:


d = {
(1, 1): commit,
(1, 0): report_that_b_failed,
(0, 0): report_that_a_failed
}


k = (a, b)
f = d[k]
f()

This approach is also really useful when you face the need to change logic based on runtime values. You can imagine that d might be built after parsing an XML file.

Ubuntu and TurboGears

It shouldn’t be so hard to set up turbogears on ubuntu Feisty Fox. The easy_install-2.4 turbogears approach crashes when trying to install Cheetah.

So, here’s a list of everything I had to do:

  • I installed the Ubuntu package for Cheetah: sudo apt-get install python-cheetah
  • Then I could run the easy install: sudo easy_install-2.4 turbogears
  • I edited /etc/apt/sources.list and added multiverse to the list of available packages. In other words, I changed this section:

deb http://archive.ubuntu.com/ubuntu/ feisty universe
deb-src http://archive.ubuntu.com/ubuntu/ feisty universe

to look like this:

deb http://archive.ubuntu.com/ubuntu/ feisty universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ feisty universe multiverse

  • Then I installed the python profiler package: sudo apt-get install python-profiler.
  • I tried installing pysqlite2 through easy_install, but that blew up, so I installed ubuntu package for pysqlite2 instead: sudo apt-get install python-pysqlite2.

Now everything works.