0
|
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 Discussions(GenshiHandler):
|
|
69 """
|
|
70 ?format=json,mbox,rss,text,snippet
|
|
71 """
|
|
72
|
|
73 template = 'index.html'
|
|
74 methods=set(['GET', 'POST'])
|
|
75
|
|
76 def __init__(self, app, request):
|
|
77 GenshiHandler.__init__(self, app, request)
|
|
78
|
|
79 def Get(self):
|
|
80 self.data['name'] = self.request.remote_user or self.app.name
|
|
81 return GenshiHandler.Get(self)
|
|
82
|
|
83 def Post(self):
|
|
84 self.app.name = self.request.POST.get('name', self.app.name)
|
|
85 self.redirect(self.link(self.handler_path))
|