Design Your URLsΒΆ

Table of Contents

The Root controller corresponds to the root URL of your web service, /. When a request for / is received, TurboGears looks for the default resource in the Root controller: the index method. The index method is the equivalent of an index.html file in a web directory.

To make the resource public, expose it with the turbogears.expose decorator:

@turbogears.expose()

Any code in an exposed method will be executed when a request for that resource is received. You can add more resources to the Root controller:

@turbogears.expose()
def about(self):
    return "This tutorial was written by Brian Beck."

View the above resource by browsing to http://localhost:8080/about.

In development mode, you should be able to see changes made to your controllers without even restarting the server.

Requests can also have parameters. These are specified in the URL for GET requests and encoded in the form input for POST requests. Both are handled the same way in your controllers: method arguments.

@turbogears.expose()
def about(self, author="Homer"):
    return "This tutorial was written by %s." % author

Now requesting /about will the same text as before, but requesting /about?author=Lisa will print:

“This tutorial was written by Lisa.”

To add more path components, just add attributes in your Root controller that are class instances containing more resources. Here I added a path component users to the Root controller:

import model

class Users:
    @turbogears.expose()
    def index(self):
        users = model.User.select()
        return ", ".join(user.email for user in users)

class Root(controllers.RootController):
    users = Users()
    ...

Now browsing to /users/index or just /users/ will print a list of the users in the database.

In addition, each user should have their own resource in the Users controller. However, this would require adding a method for every user in the database. Luckily, there is an easy way to specify dynamic path components. When a resource is requested that cannot be found in the corresponding controller, a method called default is invoked with the requested resource’s name as its argument:

class Users:
    ...

    @turbogears.expose()
    def default(self, userID):
        try:
            userID = int(userID)
        except ValueError:
            return "Invalid user ID!"

Now requesting /users/1 will print the e-mail address of the user with integer ID 1 in the database, or “No such user!” if no user with that ID exists. Requesting /users/dog will print “Invalid user ID!” since by default the user IDs in our table are integers.