0
|
1 """
|
|
2 request dispatcher:
|
|
3 data persisting across requests should go here
|
|
4 """
|
|
5
|
|
6 import os
|
|
7
|
|
8 from handlers import Index
|
|
9
|
|
10 from genshi.template import TemplateLoader
|
|
11 from paste.fileapp import FileApp
|
|
12 from pkg_resources import resource_filename
|
|
13 from webob import Request, Response, exc
|
|
14
|
|
15 class Dispatcher(object):
|
|
16
|
|
17 ### class level variables
|
|
18 defaults = { 'auto_reload': 'False',
|
|
19 }
|
|
20
|
|
21 def __init__(self, **kw):
|
|
22
|
|
23 # set instance parameters from kw and defaults
|
|
24 for key in self.defaults:
|
|
25 setattr(self, key, kw.get(key, self.defaults[key]))
|
|
26 self.auto_reload = self.auto_reload.lower() == 'true'
|
|
27
|
|
28 # request handlers
|
|
29 self.handlers = [ Index ]
|
|
30
|
|
31 # template loader
|
|
32 templates_dir = resource_filename(__name__, 'templates')
|
|
33 self.loader = TemplateLoader(templates_dir,
|
|
34 auto_reload=self.auto_reload)
|
|
35
|
|
36 def __call__(self, environ, start_response):
|
|
37
|
|
38 # get a request object
|
|
39 request = Request(environ)
|
|
40
|
|
41 # get the path
|
|
42 path = request.path_info.strip('/').split('/')
|
|
43 if path == ['']:
|
|
44 path = []
|
|
45 request.environ['path'] = path
|
|
46
|
|
47 # match the request to a handler
|
|
48 for h in self.handlers:
|
|
49 handler = h.match(self, request)
|
|
50 if handler is not None:
|
|
51 break
|
|
52 else:
|
|
53 handler = exc.HTTPNotFound
|
|
54
|
|
55 # add navigation links to handler [example]
|
|
56 if hasattr(handler, 'data'):
|
|
57 handler.data.setdefault('links', [])
|
|
58 for h in self.handlers:
|
|
59 handler.data['links'].append((handler.link(h.handler_path),
|
|
60 h.__name__))
|
|
61
|
|
62 # get response
|
|
63 res = handler()
|
|
64 return res(environ, start_response)
|