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

Last change on this file since 2468 was 2422, checked in by quentin, 15 years ago

Write handler for create form, and consolidate code to require POST into a CherryPy? tool

File size: 4.4 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                 imports=[]):
34        # Find the appropriate template lookup.
35        key = (tuple(directories), module_directory)
36        try:
37            lookup = self.lookups[key]
38        except KeyError:
39            lookup = TemplateLookup(directories=directories,
40                                    module_directory=module_directory,
41                                    collection_size=collection_size,
42                                    default_filters=['decode.utf8'],
43                                    input_encoding='utf-8',
44                                    output_encoding='utf-8',
45                                    imports=imports,
46                                    )
47            self.lookups[key] = lookup
48        cherrypy.request.lookup = lookup
49       
50        # Replace the current handler.
51        cherrypy.request.template = t = lookup.get_template(filename)
52        cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler, content_type)
53
54main = MakoLoader()
55cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
56
57class JSONEncoder(simplejson.JSONEncoder):
58        def default(self, obj):
59                if isinstance(obj, datetime.datetime):
60                        return str(obj)
61                elif isinstance(obj, decimal.Decimal):
62                        return float(obj)
63                else:
64                        return simplejson.JSONEncoder.default(self, obj)
65
66def jsonify_tool_callback(*args, **kwargs):
67    if not cherrypy.request.cached:
68        response = cherrypy.response
69        response.headers['Content-Type'] = 'text/javascript'
70        response.body = JSONEncoder().iterencode(response.body)
71
72cherrypy.tools.jsonify = cherrypy.Tool('before_finalize', jsonify_tool_callback, priority=30)
73
74def external_remote_user_login():
75    pass
76
77def require_login():
78    """If the user isn't logged in, raise 403 with an error."""
79    if cherrypy.request.login is False:
80        raise cherrypy.HTTPError(403,
81            "You are not authorized to access that resource")
82
83cherrypy.tools.require_login = cherrypy.Tool('on_start_resource', require_login, priority=150)
84
85def require_POST():
86    """If the request isn't a POST request, raise 405 Method Not Allowed"""
87    if cherrypy.request.method != "POST":
88        raise cherrypy.HTTPError(405,
89                                 "You must submit this request with POST")
90
91cherrypy.tools.require_POST = cherrypy.Tool('on_start_resource', require_POST, priority=150)
92
93def remote_user_login():
94    """Get the current user based on the SSL or GSSAPI environment variables"""
95    environ = cherrypy.request.wsgi_environ
96    user = environ.get('REMOTE_USER')
97    if user is None:
98        return
99    else:
100        cherrypy.request.login = None # clear what cherrypy put there
101
102    if environ.get('AUTH_TYPE') == 'Negotiate':
103        # Convert the krb5 principal into a krb4 username
104        if not user.endswith('@%s' % config.kerberos.realm):
105            cherrypy.request.login = False # failed to login
106        else:
107            cherrypy.request.login = user.split('@')[0].replace('/', '.')
108    else:
109        cherrypy.request.login = user
110
111cherrypy.tools.remote_user_login = cherrypy.Tool('on_start_resource', remote_user_login, priority=50)
112
113def invirtwebstate_init():
114    """Initialize the cherrypy.request.state object from Invirt"""
115    cherrypy.request.state = State(cherrypy.request.login)
116
117cherrypy.tools.invirtwebstate = cherrypy.Tool('on_start_resource', invirtwebstate_init, priority=100)
118
119class View(object):
120    _cp_config = {'tools.mako.directories': [os.path.join(os.path.dirname(__file__),'templates')]}
Note: See TracBrowser for help on using the repository browser.