4 from mako.template import Template
5 from mako.lookup import TemplateLookup
7 import datetime, decimal
9 class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
10 """Callable which sets response.body."""
12 def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
13 self.template = template
14 self.next_handler = next_handler
15 self.content_type = content_type
18 env = globals().copy()
19 env.update(self.next_handler())
20 cherrypy.response.headers['Content-Type'] = self.content_type
21 return self.template.render(**env)
24 class MakoLoader(object):
29 def __call__(self, filename, directories, module_directory=None,
30 collection_size=-1, content_type='text/html; charset=utf-8'):
31 # Find the appropriate template lookup.
32 key = (tuple(directories), module_directory)
34 lookup = self.lookups[key]
36 lookup = TemplateLookup(directories=directories,
37 module_directory=module_directory,
38 collection_size=collection_size,
39 default_filters=['decode.utf8'],
40 input_encoding='utf-8',
41 output_encoding='utf-8',
43 self.lookups[key] = lookup
44 cherrypy.request.lookup = lookup
46 # Replace the current handler.
47 cherrypy.request.template = t = lookup.get_template(filename)
48 cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
51 cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
53 class JSONEncoder(simplejson.JSONEncoder):
54 def default(self, obj):
55 if isinstance(obj, datetime.datetime):
57 elif isinstance(obj, decimal.Decimal):
60 return simplejson.JSONEncoder.default(self, obj)
62 def jsonify_tool_callback(*args, **kwargs):
63 if not cherrypy.request.cached:
64 response = cherrypy.response
65 response.headers['Content-Type'] = 'text/javascript'
66 response.body = JSONEncoder().iterencode(response.body)
68 cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
71 _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}