In CherryPy, your website is represented by a tree of objects and their methods. The way applications are set up in CherryPy, it's easy to follow how a request makes it through your system to reach its destination. How does CherryPy know where to start with a request? It starts a cherrypy.root.
If you look at the start-gs.py script, you'll see this (among other things):
By convention, your root controller class is called "Root" and it comes from the "controllers.py" module in your project's package. In a small application, one module of controllers is all you need. In a larger application, you will likely want to break your application up into separate packages. You'd want to use divisions that make sense for you. You can still import the controllers from your various packages into your controllers module, if you'd like them all available in one place.
As long as you make sure that yourpackage.controllers.Root is the root object you want for your webapp, you're all set.
Let's get a nicely contrived set of classes together to see URL lookup and controller traversal works:
With this setup, we'll be able to easily see how URL traversal works in TurboGears. These same rules apply to CherryPy even without the rest of TurboGears.
URL path | What you see | Notes |
---|---|---|
/ | Welcome | If nothing else is given, the index method is run |
/fun | ...and yet startlingly productive | If a method matches, it's run directly |
/seven | Redirect to /seven/ | Subobjects are treated like directories, so you get redirected with a slash on the end. This is a good thing, because it makes sure that your relative URLs will work. |
/seven/ | 7 | Just running the index method of the subobject |
/add/cantgohere | Error! | This method is not exposed. CherryPy will only navigate to exposed methods. |
/add/twoplustwo | four | Just running the method of the subobject |
/foobar | The next parts were ('foobar') | If no match is found for the remaining URL parts, the default method is called. |
/foobar/baz/bork | The next parts were ('foobar', 'baz', 'bork') | The remaining parts of the URL are split up and sent into the default methods as arguments. |
Between constructing your object tree however you need to and the default method, you have very sophisticated means to determine what happens when a URL is hit.