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) def external_remote_user_login(): pass def require_login(): """If the user isn't logged in, raise 403 with an error.""" if cherrypy.request.login is False: raise cherrypy.HTTPError(403, "You are not authorized to access that resource") cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login) class View(object): _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}