Posts tagged: PYTHON

Handling legacy URLs with Django

One of the great things about Django is its simple and flexible URL handling. If your Django work, like mine, includes converting existing sites, you’ll probably be doing some URL cleanup along the way. Django’s “generic views” system includes a view called “redirect_to” that handles cases like this. A rule might look like this:

urlpatterns = patterns('django.views.generic.simple',
    ('^foo/oldsite/BadOldUrl33247.blech$', 'redirect_to', {'url': '/bar/nice-new-url/'}),
    )

But because the URL pattern building happens in Python, if you have many of these you can do better than filling your urls.py with variants of that line. Here’s the root urlconf for one of my sites:

The "path" module

Somewhat belatedly I’ve started using Jason Orendorff’s path module for Python. It’s great. Here’s a comparison with the stock os.path facilities, grabbed from Jason’s site:

# with os.path.walk
def delete_backups(arg, dirname, names):
    for name in names:
        if name.endswith('~'):
            os.remove(os.path.join(dirname, name))
os.path.walk(os.environ['HOME'], delete_backups, None)

# with path
d = path(os.environ['HOME'])
for f in d.walkfiles('*~'):
    f.remove()

The second snippet is not just shorter, it’s easier to read and easier to write. I’m writing some code to recursively process a tree of short text files (Blosxom entries), and the path module is a godsend. If you’re curious, see the description and examples on Jason’s site; he also posted some interesting comments on Ian Bicking’s blog about the design of the module.

Johnny can too code

David Brin, in a piece at Salon.com entitled “Why Johnny Can’t Code”, complains:

almost none of the millions of personal computers in America offers a line-programming language simple enough for kids to pick up fast

Maybe Apple’s marketshare is so small that they equal “almost none,” but all OS X Macs come with Python and Ruby among other options. But wait, Brin seems to have heard of some of these newfangled scripting languages:

Django as superego

I built a toy site using Django’s “generic views” last night. Basically this means that for the first time I created an app without writing any real code – I defined a model, wrote some rules mapping URLs to Django’s generic view functions, and made some templates that get called by that view code (I spent most of my time fussing with the templates!).

This would have been pretty easy to hack up in PHP, too, but there are lots of things that would have been just as easy to not do the “right” way – things like clean URLs everywhere, redirect-after-POST (to avoid multiple submissions), custom error pages, a polished admin for inspecting and editing the data, nicely modular templates. Django made it easier to do it right than to do it wrong.

Enforcing Style

Browsing some programming blogs this evening I came across Ken Arnold’s provocative “Style is Substance” post from October 2004. In it, he argues that coding style variants should be eliminated by including style in the language definition:

…the only way to get from where we are to a place where we stop worrying about style is to enforce it as part of the language.

This isn’t that shocking to Python programmers (perhaps that’s why he mentions Python twice in his list of “mature” languages?). Python enforces whitespace style. To me this is one of the great joys of working with Python – my code from two years ago, or somebody else’s code in an open-source project I’m looking at, uses exactly the same indentation “conventions” that I do – because they’re not conventions, they’re requirements.

Random crufty open source release of the day

Last year a client asked for help moving his website to a new host from XO.com. The tricky part was that his 200 pages of content were locked into an obsolescent proprietary tool called “Site Builder” that offered no exporting options. The file format was a flatfile that looked like this:

#Page-Type "html"
#UID "1000"
#Access-PublicRead "on"
#Access-PublicWrite "off"
#Page-Links-Style "links_outline.nhtml"
#addbrs "off"
#hidenav "off"
#HTML ...

The file structure went like this: a parent directory named nss-objects; child directories bearing page names (or slugs, really); and inside each, an empty directory named !data and a text file named !object with the page content as described above. Weird. (I suppose every proprietary one-off system is weird in its own way, so there’s nothing to be gained from dwelling on the specifics, but at least including them in the post raises the chances that somebody who actually needs this thing and searches for it will find it.)

Moving the blog to Django

The long-awaited (by me) conversion of this blog to Django is underway. After a couple hours’ work I have a full set of models and a functioning admin, and working index and detail views of postings and comments. Searching, posting comments, and tags are the major pieces remaining. Because of my busy schedule I’ll only be able to work on it in fits and starts, but I expect the total labor in the end to be about five hours.