Mercurial > hg > MakeItSo
comparison makeitso/dispatcher.py @ 14:bf1ce840d0f0
make this a genshi view (should be: tempita view)
| author | Jeff Hammel <jhammel@mozilla.com> |
|---|---|
| date | Mon, 15 Nov 2010 08:05:55 -0800 |
| parents | |
| children | 02498337c747 |
comparison
equal
deleted
inserted
replaced
| 13:99588f138993 | 14:bf1ce840d0f0 |
|---|---|
| 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 'template_dirs': '', | |
| 20 'app': None, | |
| 21 'name': 'anonymous' } | |
| 22 | |
| 23 def __init__(self, **kw): | |
| 24 | |
| 25 # set instance parameters from kw and defaults | |
| 26 for key in self.defaults: | |
| 27 setattr(self, key, kw.get(key, self.defaults[key])) | |
| 28 self.auto_reload = self.auto_reload.lower() == 'true' | |
| 29 | |
| 30 # request handlers | |
| 31 self.handlers = [ Index ] | |
| 32 | |
| 33 # endpoint app if used as middleware | |
| 34 if self.app: | |
| 35 assert hasattr(self.app, '__call__') | |
| 36 | |
| 37 # template loader | |
| 38 self.template_dirs = self.template_dirs.split() | |
| 39 self.template_dirs.append(resource_filename(__name__, 'templates')) | |
| 40 self.loader = TemplateLoader(self.template_dirs, | |
| 41 auto_reload=self.auto_reload) | |
| 42 | |
| 43 def __call__(self, environ, start_response): | |
| 44 | |
| 45 # get a request object | |
| 46 request = Request(environ) | |
| 47 | |
| 48 # get the path | |
| 49 path = request.path_info.strip('/').split('/') | |
| 50 if path == ['']: | |
| 51 path = [] | |
| 52 request.environ['path'] = path | |
| 53 | |
| 54 # match the request to a handler | |
| 55 for h in self.handlers: | |
| 56 handler = h.match(self, request) | |
| 57 if handler is not None: | |
| 58 break | |
| 59 else: | |
| 60 if self.app: | |
| 61 return self.app(environ, start_response) | |
| 62 handler = exc.HTTPNotFound | |
| 63 | |
| 64 # add navigation links to handler [example] | |
| 65 if hasattr(handler, 'data'): | |
| 66 handler.data.setdefault('links', []) | |
| 67 for h in self.handlers: | |
| 68 handler.data['links'].append((handler.link(h.handler_path), | |
| 69 h.__name__)) | |
| 70 | |
| 71 # get response | |
| 72 res = handler() | |
| 73 return res(environ, start_response) |
