Mercurial > hg > MakeItSo
comparison makeitso/handlers.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 | 6d1c703c5ffc |
comparison
equal
deleted
inserted
replaced
13:99588f138993 | 14:bf1ce840d0f0 |
---|---|
1 """ | |
2 request handlers: | |
3 these are instantiated for every request, then called | |
4 """ | |
5 | |
6 from urlparse import urlparse | |
7 from webob import Response, exc | |
8 | |
9 class HandlerMatchException(Exception): | |
10 """the handler doesn't match the request""" | |
11 | |
12 class Handler(object): | |
13 | |
14 methods = set(['GET']) # methods to listen to | |
15 handler_path = [] # path elements to match | |
16 | |
17 @classmethod | |
18 def match(cls, app, request): | |
19 | |
20 # check the method | |
21 if request.method not in cls.methods: | |
22 return None | |
23 | |
24 # check the path | |
25 if request.environ['path'][:len(cls.handler_path)] != cls.handler_path: | |
26 return None | |
27 | |
28 try: | |
29 return cls(app, request) | |
30 except HandlerMatchException: | |
31 return None | |
32 | |
33 def __init__(self, app, request): | |
34 self.app = app | |
35 self.request = request | |
36 self.application_path = urlparse(request.application_url)[2] | |
37 | |
38 def link(self, path=(), permanant=False): | |
39 if isinstance(path, basestring): | |
40 path = [ path ] | |
41 path = [ i.strip('/') for i in path ] | |
42 if permanant: | |
43 application_url = [ self.request.application_url ] | |
44 else: | |
45 application_url = [ self.application_path ] | |
46 path = application_url + path | |
47 return '/'.join(path) | |
48 | |
49 def redirect(self, location): | |
50 raise exc.HTTPSeeOther(location=location) | |
51 | |
52 class GenshiHandler(Handler): | |
53 | |
54 def __init__(self, app, request): | |
55 Handler.__init__(self, app, request) | |
56 self.data = { 'request': request, | |
57 'link': self.link } | |
58 | |
59 def __call__(self): | |
60 return getattr(self, self.request.method.title())() | |
61 | |
62 def Get(self): | |
63 # needs to have self.template set | |
64 template = self.app.loader.load(self.template) | |
65 return Response(content_type='text/html', | |
66 body=template.generate(**self.data).render('html')) | |
67 | |
68 class Index(GenshiHandler): | |
69 template = 'index.html' | |
70 methods=set(['GET', 'POST']) | |
71 | |
72 def __init__(self, app, request): | |
73 GenshiHandler.__init__(self, app, request) | |
74 | |
75 def Get(self): | |
76 self.data['name'] = self.request.remote_user or self.app.name | |
77 return GenshiHandler.Get(self) | |
78 | |
79 def Post(self): | |
80 self.app.name = self.request.POST.get('name', self.app.name) | |
81 self.redirect(self.link(self.handler_path)) |