Introduction
Routes handles mapping URL's to controllers and their methods, or 'action's as Routes refers to them. By default, Pylons sets up the following route (found in YOURPROJ/config/routing.py):
1 | map.connect(':controller/:action/:id')
|
A part of the path beginning with a : means that it is a variable that will match that part of the URL. The default mapping can match to any of your controllers, and any of their actions, which means the following URL's will match like so:
/entry/view/4 >> controller: entry, action: view, id:4
/comment/edit/2 >> controller: comment, action: edit, id:2
Adding a route to match /
The controller and action can be specified directly in the map.connect statement, as well as the raw URL you want to match. Since the first / doesn't need to be in the route, adding the / match looks like this:
1 | map.connect('', controller='main', action='index')
|
Generating URL's
URL's can be generated using the helper method url_for, which by default in a Pylons project will be under the h global variable. Keyword arguments indicating the controller and action to use can be passed directly in:
1 | h.url_for(controller='content', action='view', id=2) # generates /content/view/2
|
Inside your templates, you might notice that other parts seem to creep into the URL's generated. This is due to Routes memory
and can be disabled by specifying the controller with a / in front like so:
1 | h.url_for(controller='/content', action='view', id=2) # generates /content/view/2
|
Keeping methods private
Since the default route will map any controller and action (method), you will probably want to prevent some methods in a controller from being callable from a URL. Routes uses the default Python convention of private methods beginning with _. To hide a method edit_generic in this class, just changing its name to begin with _ will be sufficient:
1
2
3
4
5
6
7 | class UserController(BaseController):
def index(self):
return Response("This is the index.")
def _edit_generic(self):
"I can't be called from the web!"
return True
|
Further Reference
Routes manual
For linking to the current page use an empty call to h.url_for():
One more example. If you forward a user for authentication purposes, you'd probably like to return him back to the page. To add a destination parameter, use: