view makeitso/dispatcher.py @ 22:fc2867bc2ba6

remove duplicated variable
author Jeff Hammel <jhammel@mozilla.com>
date Sun, 21 Nov 2010 12:59:47 -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)