CherryPy Project Download

====Routes URL generation====

For those who use Routes and RoutesDispatcher?, making use of the url generation capabilities can be a great timesaver.

To make Routes generate a url, call routes.url_for with keyword parameters corresponding to the Routes rules. To account for urls hidden behind mod_proxy or mod_rewrite it's also good to pass that url through cherrypy.url.

Say we have this setup:

# -*- encoding: UTF-8 -*-
import os

import cherrypy
from paste.evalexception.middleware import EvalException

class MainController:
    def index(self):
        return "This is the main page"

class BlogController:

    def index(self, entry_id):
        return "This is blog entry no. %d" % int(entry_id)

    def edit(self, entry_id):
        return "This is an edit form for blog entry no. %d" % int(entry_id)

dispatcher = None

def setup_routes():
    d = cherrypy.dispatch.RoutesDispatcher()
    d.connect('blog', 'myblog/:entry_id/:action', controller=BlogController())
    d.connect('main', ':action', controller=MainController())
    dispatcher = d
    return dispatcher

conf = {
    '/': {
        'request.dispatch': setup_routes()
    '/static': {
        'tools.staticdir.on': True,
        'tools.staticdir.root': os.path.dirname(os.path.abspath(__file__)),
        'tools.staticdir.dir': 'static'

def start(config):
    locale.setlocale(locale.LC_ALL, cherrypy.config.get('verkstjorinn.locale', ''))
    cherrypy.quickstart(None, config=conf)

if __name__ == '__main__':
    start(os.path.join(os.path.dirname(__file__), 'app.conf'))

To make use of Routes url-generation, we can for example call cherrypy.url(routes.url_for(controller="blog", action="edit", entry_id="123")) - which generates an url that goes straight to the edit form of blog entry 123. It might be something like

Calling cherrypy.url(routes.url_for(...)) is tedious, especially for a template designer, so let's make things easier:


Hosted by WebFaction

Log in as guest/cherrypy to create/edit wiki pages