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

Last change on this file since 2395 was 2391, checked in by quentin, 15 years ago

Add list method, require authentication for it, and add a hello world via mako

File size: 2.9 KB
Line 
1import os
2
3import cherrypy
4from mako.template import Template
5from mako.lookup import TemplateLookup
6import simplejson
7import datetime, decimal
8
9class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
10    """Callable which sets response.body."""
11   
12    def __init__(self, template, next_handler, content_type='text/html; charset=utf-8'):
13        self.template = template
14        self.next_handler = next_handler
15        self.content_type = content_type
16   
17    def __call__(self):
18        env = globals().copy()
19        env.update(self.next_handler())
20        cherrypy.response.headers['Content-Type'] = self.content_type
21        return self.template.render(**env)
22       
23
24class MakoLoader(object):
25   
26    def __init__(self):
27        self.lookups = {}
28   
29    def __call__(self, filename, directories, module_directory=None,
30                 collection_size=-1, content_type='text/html; charset=utf-8'):
31        # Find the appropriate template lookup.
32        key = (tuple(directories), module_directory)
33        try:
34            lookup = self.lookups[key]
35        except KeyError:
36            lookup = TemplateLookup(directories=directories,
37                                    module_directory=module_directory,
38                                    collection_size=collection_size,
39                                    default_filters=['decode.utf8'],
40                                    input_encoding='utf-8',
41                                    output_encoding='utf-8',
42                                    )
43            self.lookups[key] = lookup
44        cherrypy.request.lookup = lookup
45       
46        # Replace the current handler.
47        cherrypy.request.template = t = lookup.get_template(filename)
48        cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
49
50main = MakoLoader()
51cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
52
53class JSONEncoder(simplejson.JSONEncoder):
54        def default(self, obj):
55                if isinstance(obj, datetime.datetime):
56                        return str(obj)
57                elif isinstance(obj, decimal.Decimal):
58                        return float(obj)
59                else:
60                        return simplejson.JSONEncoder.default(self, obj)
61
62def jsonify_tool_callback(*args, **kwargs):
63    if not cherrypy.request.cached:
64        response = cherrypy.response
65        response.headers['Content-Type'] = 'text/javascript'
66        response.body = JSONEncoder().iterencode(response.body)
67
68cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
69
70def external_remote_user_login():
71    pass
72
73def require_login():
74    """If the user isn't logged in, raise 403 with an error."""
75    if cherrypy.request.login is False:
76        raise cherrypy.HTTPError(403,
77            "You are not authorized to access that resource")
78
79cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login)
80
81class View(object):
82    _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}
Note: See TracBrowser for help on using the repository browser.