view makeitso/dispatcher.py @ 26:044ac9e0b29c

add a non-working example with an include clause
author Jeff Hammel <jhammel@mozilla.com>
date Mon, 13 Dec 2010 21:03:39 -0800
parents 6d1c703c5ffc
children 1b9573832f33
line wrap: on
line source

"""
request dispatcher:
data persisting across requests should go here
"""

from handlers import Index
from webob import Request, Response, exc

class Dispatcher(object):

    ### class level variables
    defaults = { 'app': None, }

    def __init__(self, **kw):

        # set instance parameters from kw and defaults
        for key in self.defaults:
            setattr(self, key, kw.get(key, self.defaults[key]))

        # request handlers
        self.handlers = [ Index ]

        # endpoint app if used as middleware
        if self.app:
            assert hasattr(self.app, '__call__')

    def __call__(self, environ, start_response):

        # get a request object
        request = Request(environ)

        # get the path 
        path = request.path_info.strip('/').split('/')
        if path == ['']:
            path = []
        request.environ['path'] = path

        # match the request to a handler
        for h in self.handlers:
            handler = h.match(self, request)
            if handler is not None:
                break
        else:
            if self.app:
                return self.app(environ, start_response)
            handler = exc.HTTPNotFound

        # get response
        res = handler()
        return res(environ, start_response)