source: package_branches/invirt-web/cherrypy-rebased/code/view.py @ 2669

Last change on this file since 2669 was 2669, checked in by broder, 15 years ago

Get username and state from CherryPy? request

File size: 3.2 KB
Line 
1import os
2
3import cherrypy
4from mako.template import Template
5from mako.lookup import TemplateLookup
6import simplejson
7import datetime, decimal
8from invirt.config import structs as config
9from webcommon import State
10
11class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
12    """Callable which sets response.body."""
13   
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
18   
19    def __call__(self):
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)
24       
25
26class MakoLoader(object):
27   
28    def __init__(self):
29        self.lookups = {}
30   
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)
35        try:
36            lookup = self.lookups[key]
37        except KeyError:
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',
44                                    )
45            self.lookups[key] = lookup
46        cherrypy.request.lookup = lookup
47       
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)
51
52main = MakoLoader()
53cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
54
55class JSONEncoder(simplejson.JSONEncoder):
56        def default(self, obj):
57                if isinstance(obj, datetime.datetime):
58                        return str(obj)
59                elif isinstance(obj, decimal.Decimal):
60                        return float(obj)
61                else:
62                        return simplejson.JSONEncoder.default(self, obj)
63
64def 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)
69
70cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
71
72def external_remote_user_login():
73    pass
74
75def require_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")
80
81cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login)
82
83def invirtwebstate_init():
84    """Initialize the cherrypy.request.state object from Invirt"""
85    cherrypy.request.state = State(cherrypy.request.login)
86
87cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
88
89class View(object):
90    _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}
Note: See TracBrowser for help on using the repository browser.