view simplewiki/dispatcher.py @ 4:dd1c4916cbcd

[mq]: fileserver
author Jeff Hammel <jhammel@mozilla.com>
date Tue, 07 Sep 2010 22:39:15 -0700
parents 56ab6b90cd1a
children b2fbb4f982da
line wrap: on
line source

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

import os

from handlers import GenshiRenderer, Index, Post, FileServer

from genshi.template import TemplateLoader
from paste.fileapp import FileApp
from pkg_resources import resource_filename
from webob import Request, Response, exc

class Dispatcher(object):

    ### class level variables
    defaults = { 'auto_reload': 'False',
                 'template_dirs': '',
                 'name': 'anonymous',
                 'directory': 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]))
        self.auto_reload = self.auto_reload.lower() == 'true'

        assert self.directory and os.path.exists(self.directory), "Must specify an existing directory"

        # request handlers
        self.handlers = [ Post, GenshiRenderer, Index, FileServer ]

        # template loader
        self.template_dirs = self.template_dirs.split()
        self.template_dirs.append(resource_filename(__name__, 'templates'))
        self.loader = TemplateLoader(self.template_dirs,
                                     auto_reload=self.auto_reload)

    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:
            handler = exc.HTTPNotFound

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