view genshi_view/template/+package+/dispatcher.py @ 11:8a7731b2126a

include a post method, a nav bar, and some jquery fun
author k0s <k0scist@gmail.com>
date Sat, 07 Nov 2009 22:49:46 -0500
parents 55011632cf03
children 6075ca965357
line wrap: on
line source

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

import os

from handlers import Index

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',
                 'name': 'anonymous' }

    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'

        self.handlers = [ Index ]

        # static files
        self.htdocs = resource_filename(__name__, 'static')

        # template loader
        templates_dir = resource_filename(__name__, 'templates')
        self.loader = TemplateLoader(templates_dir,
                                     auto_reload=self.auto_reload)

    ### methods dealing with HTTP
    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

        # add navigation links to handler [example]
        handler.data.setdefault('links', [])
        for h in self.handlers:
            handler.data['links'].append((handler.link(h.handler_path), 
                                          h.__name__))

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