4 from mako.template import Template
5 from mako.lookup import TemplateLookup
7 import datetime, decimal
8 from invirt.config import structs as config
9 from webcommon import State
11 class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
12 """Callable which sets response.body."""
14 def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
15 self.template = template
16 self.next_handler = next_handler
17 self.content_type = content_type
20 env = globals().copy()
21 env.update(self.next_handler())
22 cherrypy.response.headers['Content-Type'] = self.content_type
23 return self.template.render(**env)
26 class MakoLoader(object):
31 def __call__(self, filename, directories, module_directory=None,
32 collection_size=-1, content_type='text/html; charset=utf-8'):
33 # Find the appropriate template lookup.
34 key = (tuple(directories), module_directory)
36 lookup = self.lookups[key]
38 lookup = TemplateLookup(directories=directories,
39 module_directory=module_directory,
40 collection_size=collection_size,
41 default_filters=['decode.utf8'],
42 input_encoding='utf-8',
43 output_encoding='utf-8',
45 self.lookups[key] = lookup
46 cherrypy.request.lookup = lookup
48 # Replace the current handler.
49 cherrypy.request.template = t = lookup.get_template(filename)
50 cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
53 cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
55 class JSONEncoder(simplejson.JSONEncoder):
56 def default(self, obj):
57 if isinstance(obj, datetime.datetime):
59 elif isinstance(obj, decimal.Decimal):
62 return simplejson.JSONEncoder.default(self, obj)
64 def jsonify_tool_callback(*args, **kwargs):
65 if not cherrypy.request.cached:
66 response = cherrypy.response
67 response.headers['Content-Type'] = 'text/javascript'
68 response.body = JSONEncoder().iterencode(response.body)
70 cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
72 def external_remote_user_login():
76 """If the user isn't logged in, raise 403 with an error."""
77 if cherrypy.request.login is False:
78 raise cherrypy.HTTPError(403,
79 "You are not authorized to access that resource")
81 cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login)
83 def invirtwebstate_init():
84 """Initialize the cherrypy.request.state object from Invirt"""
85 cherrypy.request.state = State(cherrypy.request.login)
87 cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
90 _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}