comparison taginthemiddle/middleware.py @ 0:1c5cbbde4299

initial commit of middleware tagging; doesnt yet work
author Jeff Hammel <jhammel@mozilla.com>
date Tue, 04 May 2010 08:37:15 -0700
parents
children 837cfc05d4d9
comparison
equal deleted inserted replaced
-1:000000000000 0:1c5cbbde4299
1 """
2 request dispatcher:
3 data persisting across requests should go here
4 """
5
6 import os
7
8 from handlers import Index
9 from model import Tags
10
11 from genshi.template import TemplateLoader
12 from lxmlmiddleware import LXMLMiddleware
13 from paste.fileapp import FileApp
14 from pkg_resources import resource_filename
15 from webob import Request, Response, exc
16
17 # tags have:
18 # - a list of resources they're applied to
19 # for now just assume auth is on and that anyone authenticated may tag
20
21 # e.g. a tags file
22 # foo = /bar /fleem/baz etc
23 # cats = /cats /blog/mycat
24
25 class Tagger(LXMLMiddleware):
26
27 # instance defaults
28 defaults = { 'auto_reload': 'False',
29 'template_dirs': '',
30 'patterns': '*'
31 'tags_file': None,
32 'url': 'tags'
33 'post_url': '.tags'
34 }
35
36 def __init__(self, app, **kw):
37 self.app = app
38
39 # set instance parameters from kw and defaults
40 for key in self.defaults:
41 setattr(self, key, kw.get(key, self.defaults[key]))
42 self.auto_reload = self.auto_reload.lower() == 'true'
43 assert self.tags_file is not None
44 self.tags
45 self.patterns = self.patterns.strip().split()
46
47 # request handlers
48 self.handlers = [ Cloud ]
49
50 # template loader
51 self.template_dirs = self.template_dirs.split()
52 self.template_dirs.append(resource_filename(__name__, 'templates'))
53 self.loader = TemplateLoader(self.template_dirs,
54 auto_reload=self.auto_reload)
55
56 def __call__(self, environ, start_response):
57
58 # get a request object
59 request = Request(environ)
60
61 # get the path
62 path = request.path_info.strip('/').split('/')
63 if path == ['']:
64 path = []
65 request.environ['path'] = path
66
67 # match the request to a handler
68 for h in self.handlers:
69 handler = h.match(self, request)
70 if handler is not None:
71 break
72 else:
73 if self.app:
74 return self.app(environ, start_response)
75 handler = exc.HTTPNotFound
76
77 # add navigation links to handler [example]
78 if hasattr(handler, 'data'):
79 handler.data.setdefault('links', [])
80 for h in self.handlers:
81 handler.data['links'].append((handler.link(h.handler_path),
82 h.__name__))
83
84 # get response
85 res = handler()
86 return res(environ, start_response)