comparison makeitso/dispatcher.py @ 48:1b9573832f33

clean up the dispatcher code
author Jeff Hammel <jhammel@mozilla.com>
date Wed, 05 Jan 2011 18:26:07 -0800
parents 6d1c703c5ffc
children
comparison
equal deleted inserted replaced
47:e8d5782f6678 48:1b9573832f33
1 """ 1 """
2 request dispatcher: 2 request dispatcher for MakeItSo!
3 data persisting across requests should go here
4 """ 3 """
5 4
5 import sys
6 from handlers import Index 6 from handlers import Index
7 from webob import Request, Response, exc 7 from webob import Request, Response, exc
8 8
9 class Dispatcher(object): 9 class Dispatcher(object):
10 10
11 ### class level variables 11 ### class level variables
12 defaults = { 'app': None, }
13 12
14 def __init__(self, **kw): 13 def __init__(self, **kw):
15 14
16 # set instance parameters from kw and defaults
17 for key in self.defaults:
18 setattr(self, key, kw.get(key, self.defaults[key]))
19
20 # request handlers 15 # request handlers
21 self.handlers = [ Index ] 16 self.handlers = [ Index ]
22
23 # endpoint app if used as middleware
24 if self.app:
25 assert hasattr(self.app, '__call__')
26 17
27 def __call__(self, environ, start_response): 18 def __call__(self, environ, start_response):
28 19
29 # get a request object 20 # get a request object
30 request = Request(environ) 21 request = Request(environ)
39 for h in self.handlers: 30 for h in self.handlers:
40 handler = h.match(self, request) 31 handler = h.match(self, request)
41 if handler is not None: 32 if handler is not None:
42 break 33 break
43 else: 34 else:
44 if self.app:
45 return self.app(environ, start_response)
46 handler = exc.HTTPNotFound 35 handler = exc.HTTPNotFound
47 36
48 # get response 37 # get response
49 res = handler() 38 res = handler()
50 return res(environ, start_response) 39 return res(environ, start_response)
40
41 if __name__ == '__main__':
42 from optparse import OptionParser
43 from wsgiref import simple_server
44
45 # parse command line options
46 parser = OptionParser()
47 parser.add_option('-p', '--port', dest='port', default=8080, type='int',
48 help='port to serve on')
49 options, args = parser.parse_args()
50
51 # create an app
52 app = Dispatcher()
53
54 # serve it!
55 server = simple_server.make_server(host=host, port=options.port, app=app)
56 server.serve_forever()