Mako and SimpleJSON CherryPy hooks
authorQuentin Smith <quentin@mit.edu>
Sun, 9 Aug 2009 22:45:18 +0000 (18:45 -0400)
committerQuentin Smith <quentin@mit.edu>
Sun, 9 Aug 2009 22:45:18 +0000 (18:45 -0400)
svn path=/package_branches/invirt-web/cherrypy-rebased/; revision=2659

code/view.py [new file with mode: 0644]

diff --git a/code/view.py b/code/view.py
new file mode 100644 (file)
index 0000000..a375a9e
--- /dev/null
@@ -0,0 +1,71 @@
+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')]}