--- /dev/null
+import os
+
+import cherrypy
+from mako.template import Template
+from mako.lookup import TemplateLookup
+import simplejson
+import datetime, decimal
+
+class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
+ """Callable which sets response.body."""
+
+ def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
+ self.template = template
+ self.next_handler = next_handler
+ self.content_type = content_type
+
+ def __call__(self):
+ env = globals().copy()
+ env.update(self.next_handler())
+ cherrypy.response.headers['Content-Type'] = self.content_type
+ return self.template.render(**env)
+
+
+class MakoLoader(object):
+
+ def __init__(self):
+ self.lookups = {}
+
+ def __call__(self, filename, directories, module_directory=None,
+ collection_size=-1, content_type='text/html; charset=utf-8'):
+ # Find the appropriate template lookup.
+ key = (tuple(directories), module_directory)
+ try:
+ lookup = self.lookups[key]
+ except KeyError:
+ lookup = TemplateLookup(directories=directories,
+ module_directory=module_directory,
+ collection_size=collection_size,
+ default_filters=['decode.utf8'],
+ input_encoding='utf-8',
+ output_encoding='utf-8',
+ )
+ self.lookups[key] = lookup
+ cherrypy.request.lookup = lookup
+
+ # Replace the current handler.
+ cherrypy.request.template = t = lookup.get_template(filename)
+ cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
+
+main = MakoLoader()
+cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
+
+class JSONEncoder(simplejson.JSONEncoder):
+ def default(self, obj):
+ if isinstance(obj, datetime.datetime):
+ return str(obj)
+ elif isinstance(obj, decimal.Decimal):
+ return float(obj)
+ else:
+ return simplejson.JSONEncoder.default(self, obj)
+
+def jsonify_tool_callback(*args, **kwargs):
+ if not cherrypy.request.cached:
+ response = cherrypy.response
+ response.headers['Content-Type'] = 'text/javascript'
+ response.body = JSONEncoder().iterencode(response.body)
+
+cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
+
+class View(object):
+ _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}