1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
1 |
# IVLE - Informatics Virtual Learning Environment
|
2 |
# Copyright (C) 2007-2009 The University of Melbourne
|
|
3 |
#
|
|
4 |
# This program is free software; you can redistribute it and/or modify
|
|
5 |
# it under the terms of the GNU General Public License as published by
|
|
6 |
# the Free Software Foundation; either version 2 of the License, or
|
|
7 |
# (at your option) any later version.
|
|
8 |
#
|
|
9 |
# This program is distributed in the hope that it will be useful,
|
|
10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
12 |
# GNU General Public License for more details.
|
|
13 |
#
|
|
14 |
# You should have received a copy of the GNU General Public License
|
|
15 |
# along with this program; if not, write to the Free Software
|
|
16 |
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
|
17 |
||
1165.3.4
by Nick Chadwick
Fixed an omission in XHTMLRESTView in which a template which had not |
18 |
# Author: Matt Giuca, Will Grant, Nick Chadwick
|
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
19 |
|
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
20 |
import cgi |
21 |
import functools |
|
22 |
import inspect |
|
1165.3.4
by Nick Chadwick
Fixed an omission in XHTMLRESTView in which a template which had not |
23 |
import os |
1099.4.1
by Nick Chadwick
Working on putting worksheets into the database. |
24 |
import urlparse |
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
25 |
|
26 |
import cjson |
|
1165.2.1
by Nick Chadwick
Added an XHTMLRESTView, which returns normal json, with the addition |
27 |
import genshi.template |
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
28 |
|
29 |
from ivle.webapp.base.views import BaseView |
|
1720
by William Grant
Share one TemplateLoader between every instance of every view, so we cache EVERYTHING. |
30 |
from ivle.webapp.base.xhtml import GenshiLoaderMixin |
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
31 |
from ivle.webapp.errors import BadRequest, MethodNotAllowed, Unauthorized |
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
32 |
|
33 |
class RESTView(BaseView): |
|
34 |
"""
|
|
35 |
A view which provides a RESTful interface. The content type is
|
|
36 |
unspecified (see JSONRESTView for a specific content type).
|
|
37 |
"""
|
|
38 |
content_type = "application/octet-stream" |
|
39 |
||
40 |
def render(self, req): |
|
1099.1.52
by William Grant
ivle.webapp.base.rest#RESTView: Remove broken old render() - it should be |
41 |
raise NotImplementedError() |
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
42 |
|
43 |
class JSONRESTView(RESTView): |
|
44 |
"""
|
|
45 |
A special case of RESTView which deals entirely in JSON.
|
|
46 |
"""
|
|
47 |
content_type = "application/json" |
|
48 |
||
49 |
_allowed_methods = property( |
|
50 |
lambda self: [m for m in ('GET', 'PUT', 'PATCH') |
|
51 |
if hasattr(self, m)] + ['POST']) |
|
52 |
||
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
53 |
def authorize(self, req): |
54 |
return True # Real authz performed in render(). |
|
55 |
||
56 |
def authorize_method(self, req, op): |
|
57 |
if not hasattr(op, '_rest_api_permission'): |
|
58 |
raise Unauthorized() |
|
59 |
||
1544
by Matt Giuca
Added an argument 'config' to every single get_permissions method throughout the program. All calls to get_permissions pass a config. This is to allow per-site policy configurations on permissions. |
60 |
if (op._rest_api_permission not in |
61 |
self.get_permissions(req.user, req.config)): |
|
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
62 |
raise Unauthorized() |
1099.4.3
by Nick Chadwick
Updated the tutorial service, to now allow users to edit worksheets |
63 |
|
64 |
def convert_bool(self, value): |
|
1099.1.188
by Nick Chadwick
Fixed a slight issue in convert_bool, which now uses a tuple, and |
65 |
if value in ('True', 'true', True): |
1099.4.3
by Nick Chadwick
Updated the tutorial service, to now allow users to edit worksheets |
66 |
return True |
1099.1.188
by Nick Chadwick
Fixed a slight issue in convert_bool, which now uses a tuple, and |
67 |
elif value in ('False', 'false', False): |
1099.4.3
by Nick Chadwick
Updated the tutorial service, to now allow users to edit worksheets |
68 |
return False |
69 |
else: |
|
70 |
raise BadRequest() |
|
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
71 |
|
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
72 |
def render(self, req): |
73 |
if req.method not in self._allowed_methods: |
|
74 |
raise MethodNotAllowed(allowed=self._allowed_methods) |
|
75 |
||
76 |
if req.method == 'GET': |
|
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
77 |
qargs = dict(cgi.parse_qsl( |
1796.1.3
by William Grant
Use req.unparsed_uri instead of req.uri -- req.uri doesn't contain the query string. |
78 |
urlparse.urlparse(req.unparsed_uri).query, |
79 |
keep_blank_values=1)) |
|
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
80 |
if 'ivle.op' in qargs: |
81 |
outjson = self._named_operation(req, qargs, readonly=True) |
|
82 |
else: |
|
83 |
self.authorize_method(req, self.GET) |
|
84 |
outjson = self.GET(req) |
|
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
85 |
# Since PATCH isn't yet an official HTTP method, we allow users to
|
86 |
# turn a PUT into a PATCH by supplying a special header.
|
|
87 |
elif req.method == 'PATCH' or (req.method == 'PUT' and |
|
88 |
'X-IVLE-Patch-Semantics' in req.headers_in and |
|
89 |
req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'): |
|
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
90 |
self.authorize_method(req, self.PATCH) |
1099.1.53
by William Grant
ivle.webapp.base.rest#JSONRESTView: Check for bad JSON input, rather than |
91 |
try: |
92 |
input = cjson.decode(req.read()) |
|
93 |
except cjson.DecodeError: |
|
94 |
raise BadRequest('Invalid JSON data') |
|
95 |
outjson = self.PATCH(req, input) |
|
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
96 |
elif req.method == 'PUT': |
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
97 |
self.authorize_method(req, self.PUT) |
1099.1.53
by William Grant
ivle.webapp.base.rest#JSONRESTView: Check for bad JSON input, rather than |
98 |
try: |
99 |
input = cjson.decode(req.read()) |
|
100 |
except cjson.DecodeError: |
|
101 |
raise BadRequest('Invalid JSON data') |
|
102 |
outjson = self.PUT(req, input) |
|
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
103 |
# POST implies named operation.
|
104 |
elif req.method == 'POST': |
|
105 |
# TODO: Check Content-Type and implement multipart/form-data.
|
|
1099.4.1
by Nick Chadwick
Working on putting worksheets into the database. |
106 |
data = req.read() |
1099.4.3
by Nick Chadwick
Updated the tutorial service, to now allow users to edit worksheets |
107 |
opargs = dict(cgi.parse_qsl(data, keep_blank_values=1)) |
1796.1.1
by William Grant
Factor out named operation execution, so we can tie it into the GET handler too. |
108 |
outjson = self._named_operation(req, opargs) |
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
109 |
|
110 |
req.content_type = self.content_type |
|
1165.2.1
by Nick Chadwick
Added an XHTMLRESTView, which returns normal json, with the addition |
111 |
self.write_json(req, outjson) |
112 |
||
113 |
#This is a separate function to allow additional data to be passed through
|
|
114 |
def write_json(self, req, outjson): |
|
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
115 |
if outjson is not None: |
116 |
req.write(cjson.encode(outjson)) |
|
117 |
req.write("\n") |
|
118 |
||
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
119 |
def _named_operation(self, req, opargs, readonly=False): |
1796.1.1
by William Grant
Factor out named operation execution, so we can tie it into the GET handler too. |
120 |
try: |
121 |
opname = opargs['ivle.op'] |
|
122 |
del opargs['ivle.op'] |
|
123 |
except KeyError: |
|
124 |
raise BadRequest('No named operation specified.') |
|
125 |
||
126 |
try: |
|
127 |
op = getattr(self, opname) |
|
128 |
except AttributeError: |
|
129 |
raise BadRequest('Invalid named operation.') |
|
130 |
||
131 |
if not hasattr(op, '_rest_api_callable') or \ |
|
132 |
not op._rest_api_callable: |
|
133 |
raise BadRequest('Invalid named operation.') |
|
134 |
||
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
135 |
if readonly and op._rest_api_write_operation: |
136 |
raise BadRequest('POST required for write operation.') |
|
137 |
||
1796.1.1
by William Grant
Factor out named operation execution, so we can tie it into the GET handler too. |
138 |
self.authorize_method(req, op) |
139 |
||
140 |
# Find any missing arguments, except for the first two (self, req)
|
|
141 |
(args, vaargs, varkw, defaults) = inspect.getargspec(op) |
|
142 |
args = args[2:] |
|
143 |
||
144 |
# To find missing arguments, we eliminate the provided arguments
|
|
145 |
# from the set of remaining function signature arguments. If the
|
|
146 |
# remaining signature arguments are in the args[-len(defaults):],
|
|
147 |
# we are OK.
|
|
148 |
unspec = set(args) - set(opargs.keys()) |
|
149 |
if unspec and not defaults: |
|
150 |
raise BadRequest('Missing arguments: ' + ', '.join(unspec)) |
|
151 |
||
152 |
unspec = [k for k in unspec if k not in args[-len(defaults):]] |
|
153 |
||
154 |
if unspec: |
|
155 |
raise BadRequest('Missing arguments: ' + ', '.join(unspec)) |
|
156 |
||
157 |
# We have extra arguments if the are no match args in the function
|
|
158 |
# signature, AND there is no **.
|
|
159 |
extra = set(opargs.keys()) - set(args) |
|
160 |
if extra and not varkw: |
|
161 |
raise BadRequest('Extra arguments: ' + ', '.join(extra)) |
|
162 |
||
163 |
return op(req, **opargs) |
|
164 |
||
1165.2.1
by Nick Chadwick
Added an XHTMLRESTView, which returns normal json, with the addition |
165 |
|
1720
by William Grant
Share one TemplateLoader between every instance of every view, so we cache EVERYTHING. |
166 |
class XHTMLRESTView(GenshiLoaderMixin, JSONRESTView): |
1165.2.1
by Nick Chadwick
Added an XHTMLRESTView, which returns normal json, with the addition |
167 |
"""A special type of RESTView which takes enhances the standard JSON
|
168 |
with genshi XHTML functions.
|
|
169 |
|
|
170 |
XHTMLRESTViews should have a template, which is rendered using their
|
|
171 |
context. This is returned in the JSON as 'html'"""
|
|
172 |
template = None |
|
173 |
ctx = genshi.template.Context() |
|
174 |
||
175 |
def render_fragment(self): |
|
176 |
if self.template is None: |
|
177 |
raise NotImplementedError() |
|
178 |
||
1165.3.4
by Nick Chadwick
Fixed an omission in XHTMLRESTView in which a template which had not |
179 |
rest_template = os.path.join(os.path.dirname( |
180 |
inspect.getmodule(self).__file__), self.template) |
|
1720
by William Grant
Share one TemplateLoader between every instance of every view, so we cache EVERYTHING. |
181 |
tmpl = self._loader.load(rest_template) |
1165.3.4
by Nick Chadwick
Fixed an omission in XHTMLRESTView in which a template which had not |
182 |
|
1165.2.1
by Nick Chadwick
Added an XHTMLRESTView, which returns normal json, with the addition |
183 |
return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml') |
184 |
||
185 |
# This renders the template and adds it to the json
|
|
186 |
def write_json(self, req, outjson): |
|
187 |
outjson["html"] = self.render_fragment() |
|
188 |
req.write(cjson.encode(outjson)) |
|
189 |
req.write("\n") |
|
190 |
||
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
191 |
class _named_operation(object): |
1099.1.34
by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was |
192 |
'''Declare a function to be accessible to HTTP users via the REST API.
|
193 |
'''
|
|
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
194 |
def __init__(self, write_operation, permission): |
195 |
self.write_operation = write_operation |
|
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
196 |
self.permission = permission |
197 |
||
198 |
def __call__(self, func): |
|
199 |
func._rest_api_callable = True |
|
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
200 |
func._rest_api_write_operation = self.write_operation |
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
201 |
func._rest_api_permission = self.permission |
202 |
return func |
|
203 |
||
1796.1.2
by William Grant
Replace @named_operation with @read_operation and @write_operation. Allow execution of read operations with a GET rather than a POST. |
204 |
write_operation = functools.partial(_named_operation, True) |
205 |
read_operation = functools.partial(_named_operation, False) |
|
206 |
||
1099.1.112
by William Grant
Implement authorization in JSON REST views. Add security declarations to |
207 |
class require_permission(object): |
208 |
'''Declare the permission required for use of a method via the REST API.
|
|
209 |
'''
|
|
210 |
def __init__(self, permission): |
|
211 |
self.permission = permission |
|
212 |
||
213 |
def __call__(self, func): |
|
214 |
func._rest_api_permission = self.permission |
|
215 |
return func |