Code example that allows you to choose a controller based on a url. This is an example: myapp/config/routing.py
"""Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
from pylons import config
from routes import Mapper
from formalchemy.ext.pylons import maps # routes generator
class SuperMapper(Mapper):
"""
Allows us to have a dynamic controller, and injects an extra param
"""
def _match(self, url):
"""
Just works out a better controller
"""
result = super(SuperMapper, self)._match(url)
if result[0] is not None and result[0]['controller'] == 'DYNAMIC':
url = result[0].get('url', url)
if url.startswith('/'):
url = url[1:]
result[0]['extraInfo'] = makeUpSomExtraInfoBasedOnTheURL(url)
# Just return a string name like 'root' for example
result[0]['controller'] = chooseSomeOtherControllerNameBasedOnTheURL(url)
return result
def make_map():
"""Create, configure and return the routes Mapper"""
map = SuperMapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
map.minimization = True
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be resolved
map.connect('/error/{action}', controller='error')
map.connect('/error/{action}/{id}', controller='error')
# CUSTOM ROUTES HERE
# Map the /admin url to FA's AdminController
maps.admin_map(map, controller='admin', url='/admin')
map.connect('/index', controller='DYNAMIC', action='view', url='index')
map.connect('/edit', controller='DYNAMIC', action='edit', url='index')
map.connect('/*(url)/edit', controller='DYNAMIC', action='edit')
map.connect('/*(url)', controller='DYNAMIC', action='view')
return map