view taginthemiddle/middleware.py @ 19:57ca873ed9bf default tip

make this a pluggable system and start reorging infrastructure for that
author Jeff Hammel <jhammel@mozilla.com>
date Tue, 25 May 2010 07:48:53 -0700
parents 1701e5b0b0eb
children
line wrap: on
line source

"""
apply and display tags via WSGI middleware;
request dispatcher component
"""

import os

from handlers import TagCloud, ViewTags, PostTags

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

class Tagger(LXMLMiddleware):

    # instance defaults
    defaults = { 'auto_reload': 'False',
                 'template_dirs': '',
                 'patterns': '*', # glob pattern: all URLs by default
                 'tags_url': 'tags', # base URL for viewing tags
                 'post_url': '.tags', # sub-URL for posting tags
                 'author': None, # for RSS
                 'engine': None
                 }

    def __init__(self, app, **kw):
        self.app = app

        # 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.patterns = self.patterns.strip().split()

        # request handlers
        self.handlers = [ TagCloud, ViewTags, PostTags ]

        # 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)

        # tag engine
        assert self.engine is not None, 'Must specify a tag.engine'

    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)

    def manipulate(self, request, response, tree):
        return tree