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