Pretty URLs: Routes in Google App Engine

Pretty URLs are an essential element of web applications. Pretty URLs are helpful to users, influential for SEO and implementations may enhance the beauty (and so the extensibility and maintainability) of a code base. This is superbly achieved in Google App Engine using Rodrigo Moraes’ App Engine recipe for URL mapping using Routes.

I discussed in a previous post how I used a basic implementation of GAE’s WSGIApplication for Pretty URL mapping. While this approach served my initial needs, it required a lot of extra logic to read params from incoming URLs and did not elegantly handle URLs invoked in an AJAX call (i.e. logic was need in the handler to interpret the URL and delegate to the appropriate action). My goal was to implement a Pretty URL mapping scheme that allowed me to:

  • configure URL mappings in one place only
  • gracefully pass params on URLs
  • invoke actions contained in my handlers

Happily, I stumbled upon Moraes’ recipe; it was a snap to follow the very clear directions to import Routes and override the WSGIApplication. Further support from the Routes documentation allowed me to quickly and easily meet all my Pretty URL goals.

All URL mappings are configured in Params passed on URLs are discretely mapped and retrieved. For instance this mapping accepts a param named ‘id’ and hits a handler in called ‘MyHandler':

map.connect('handler/:id', controller = 'views:MyHandler')

In, ‘id’ is picked up as an argument of the get() method:

class MyHandler(ParentHandler):def get(self, id): ...

How cool is that?! Crisp and clean and no caffeine. It gets better.

I can also map to a handler and an action. This is particularly handy for my, which accepts AJAX requests. With this mapping the correct handler’s action is invoked without any messy delegation at the top of my

map.connect('api/handler/action', controller = 'api:MyHandler', action = 'action')

How great is this? Pretty URLs and cleaner code. Yes, I’ve added the Routes resources and Moraes’ overridden WSGIApplication, but the separation of mapping logic from other aspects of the application pleases me and I believe makes for a more robust code base. Not to mention, I learned a new thing! Thanks Mr Moraes, my URLs got pulchriTUDE!



  1. says

    Thanks yo, I appreciate your comment. Indeed I vaguely remember looking at this option when I was working through this implementation a few months back; grateful to have it back in my attention. I am liking the routes recipe we've been using since I wrote this. Nice for passing around params and from the helpful message you've left on Luc Russell's blog, you'll know we used it to create slugs. Defo fast take up and elegant separation of concerns, imho. All the best for the new year!