comparison genshi_view/template/+package+/handlers.py @ 21:807c8eef8098

add a handler for tempita; should rename the package (at some point) template_view
author Jeff Hammel <jhammel@mozilla.com>
date Wed, 17 Nov 2010 11:02:33 -0800
parents d54f85043f77
children
comparison
equal deleted inserted replaced
20:cf19d2e129de 21:807c8eef8098
1 """ 1 """
2 request handlers: 2 request handlers:
3 these are instantiated for every request, then called 3 these are instantiated for every request, then called
4 """ 4 """
5 5
6 import os
7 from pkg_resources import resource_filename
6 from urlparse import urlparse 8 from urlparse import urlparse
7 from webob import Response, exc 9 from webob import Response, exc
10 from tempita import HTMLTemplate
8 11
9 class HandlerMatchException(Exception): 12 class HandlerMatchException(Exception):
10 """the handler doesn't match the request""" 13 """the handler doesn't match the request"""
11 14
12 class Handler(object): 15 class Handler(object):
47 return '/'.join(path) 50 return '/'.join(path)
48 51
49 def redirect(self, location): 52 def redirect(self, location):
50 raise exc.HTTPSeeOther(location=location) 53 raise exc.HTTPSeeOther(location=location)
51 54
55 class TempitaHandler(Handler):
56
57 template_dirs = [ resource_filename(__name__, 'templates') ]
58
59 def __init__(self, app, request):
60 Handler.__init__(self, app, request)
61 self.data = { 'request': request,
62 'link': self.link }
63
64 def __call__(self):
65 return getattr(self, self.request.method.title())()
66
67 def find_template(self, template):
68 for d in self.template_dirs:
69 path = os.path.join(d, template)
70 if os.path.exists(path):
71 return HTMLTemplate.from_filename(path)
72
73 def Get(self):
74 # needs to have self.template set
75 template = self.find_template(self.template)
76 return Response(content_type='text/html',
77 body=template.substitute(**self.data))
78
79
52 class GenshiHandler(Handler): 80 class GenshiHandler(Handler):
53 81
54 def __init__(self, app, request): 82 def __init__(self, app, request):
55 Handler.__init__(self, app, request) 83 Handler.__init__(self, app, request)
56 self.data = { 'request': request, 84 self.data = { 'request': request,
63 # needs to have self.template set 91 # needs to have self.template set
64 template = self.app.loader.load(self.template) 92 template = self.app.loader.load(self.template)
65 return Response(content_type='text/html', 93 return Response(content_type='text/html',
66 body=template.generate(**self.data).render('html')) 94 body=template.generate(**self.data).render('html'))
67 95
96
97
68 class Index(GenshiHandler): 98 class Index(GenshiHandler):
69 template = 'index.html' 99 template = 'index.html'
70 methods=set(['GET', 'POST']) 100 methods=set(['GET', 'POST'])
71 101
72 def __init__(self, app, request): 102 def __init__(self, app, request):