zachary.com

personal pages

All ad proceeds donated to charity.

sixtyPercent: Cochlear Implants, Aviation, Technlology, and Philosophy 2005/10/01

Integrating CherryPy and Routes

Here's a very simplistic example of integrating CherryPy and Routes for URL mapping.

The basic approach is to place the Routes Mapper at the root of the CherryPy object publisher as a catch-all method. It then takes over URL to object dispatching.

This examples uses CherryPy 2.0, but 2.1 should be even simpler. I'm not entirely sure what to do about the CherryPy "default" method -- the example below doesn't quite get it right.

from cherrypy.lib import httptools
from cherrypy.cperror import NotFound
from cherrypy import cpg

import re
base_re = re.compile( r'^(?P[a-zA-Z]+)://(?P.*)' )

class RouteRoot:
    def default( self, *args, **kwargs ):
        
        base = cpg.request.base
        d = base_re.match( base ).groupdict()
        host = d[ 'host' ]
        proto = d[ 'protocol' ]
        path = cpg.request.path

        con = request_config()
        con.mapper = m # the Routes Mapper object
        con.host = host
        con.protocol = proto
        con.redirect = httptools.redirect
        con.mapper_dict = m.match( path )

        if con.mapper_dict:
            c = con.mapper_dict.pop( 'controller' )
            controller = controllers[c]
            action = con.mapper_dict.pop( 'action', 'index' )
            try:
                meth = controller.__getattribute__( action )
            except AttributeError:
                try:
                    meth = controller.__getattribute__( 'default' )
                except AttributeError:
                    raise NotFound( path )
            kwargs.update( con.mapper_dict )
            print meth, kwargs
            return meth( **kwargs )

        raise NotFound( path )
    default.exposed = True
    
cpg.root = RouteRoot()


***
highlight file error
***

by David Creemer : 2005/10/01 : Categories python (permalink)



All content Copyright 2003-2005, David Z Creemer