0
|
1 """
|
|
2 request dispatcher:
|
|
3 data persisting across requests should go here
|
|
4 """
|
|
5
|
|
6 import os
|
|
7
|
5
|
8 from handlers import GenshiRenderer, Index, Post, FileServer, EditView
|
0
|
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': '',
|
1
|
20 'name': 'anonymous',
|
|
21 'directory': None }
|
0
|
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
|
1
|
30 assert self.directory and os.path.exists(self.directory), "Must specify an existing directory"
|
0
|
31
|
1
|
32 # request handlers
|
5
|
33 self.handlers = [ Post, EditView, GenshiRenderer, Index, FileServer ]
|
0
|
34
|
|
35 # template loader
|
|
36 self.template_dirs = self.template_dirs.split()
|
|
37 self.template_dirs.append(resource_filename(__name__, 'templates'))
|
|
38 self.loader = TemplateLoader(self.template_dirs,
|
|
39 auto_reload=self.auto_reload)
|
|
40
|
|
41 def __call__(self, environ, start_response):
|
|
42
|
|
43 # get a request object
|
|
44 request = Request(environ)
|
|
45
|
|
46 # get the path
|
|
47 path = request.path_info.strip('/').split('/')
|
|
48 if path == ['']:
|
|
49 path = []
|
|
50 request.environ['path'] = path
|
|
51
|
|
52 # match the request to a handler
|
|
53 for h in self.handlers:
|
|
54 handler = h.match(self, request)
|
|
55 if handler is not None:
|
|
56 break
|
|
57 else:
|
|
58 handler = exc.HTTPNotFound
|
|
59
|
|
60 # get response
|
|
61 res = handler()
|
|
62 return res(environ, start_response)
|