view makeitso/dispatcher.py @ 39:a2cdce0108e1

get directory substitution sorta working; start stubbing mixed case
author Jeff Hammel <jhammel@mozilla.com>
date Sat, 01 Jan 2011 23:00:59 -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)