Basic page routing with CherryPy

My last CherryPy post covered how to set up a very basic site using the quickstart() function. This time, I'm going to go into some basic details on page handling..

The first thing we're going to do is define a class for handling the root of our site.

~~~~ {.python name="code"} class Root: def index(self): return "This is the root" = Trueif __name__ == "__main__": root = Root() cherrypy.tree.mount(root, '/') cherrypy.engine.start() cherrypy.engine.block() wzxhzdk:0

See the line starting with root.names =? That's going to set up a handler for the url http://localhost:8080/names.

Let's look at the definition of the NamesPage() class. The simplest would be something just like the Root() class.

~~~~ {.python name="code"} class NamesPage: def index(self): return "This is the root" = True wzxhzdk:1

You can see how the first part of the request URI maps to the index method of the page handler class. The next part of the request URI maps to any method in the routing class with a matching name.

The next neat bit about routing comes into play when the last part of the URI doesn't match any defined methods. For example, how do we handle the url http://localhost:8080/names/mark?

As the NamesPage() class stands now, we'll end up with a 404 exception. But, by using the default() method in the NamesPage() class, we can handle it in a very cool way.

~~~~ {.python name="code"} class NamesPage: def default(self, name=None): return "Hello " + name = True def help(self): return "This is the help page" = True ~~~~

With this definition of NamesPage(), everything that comes after "/names/" (except for help/) gets passed as an argument to the default() method.

The above is a pretty simple summary. There's a lot more that can be done as you can see from the PageHandlers documentation.