1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2009 The University of Melbourne
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.
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.
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
18
# Author: Matt Giuca, Will Grant
25
from ivle.webapp.base.views import BaseView
26
from ivle.webapp.errors import BadRequest, MethodNotAllowed
28
class RESTView(BaseView):
30
A view which provides a RESTful interface. The content type is
31
unspecified (see JSONRESTView for a specific content type).
33
content_type = "application/octet-stream"
35
def __init__(self, req, *args, **kwargs):
37
setattr(self, key, kwargs[key])
39
def render(self, req):
40
raise NotImplementedError()
42
class JSONRESTView(RESTView):
44
A special case of RESTView which deals entirely in JSON.
46
content_type = "application/json"
48
_allowed_methods = property(
49
lambda self: [m for m in ('GET', 'PUT', 'PATCH')
50
if hasattr(self, m)] + ['POST'])
52
def render(self, req):
53
if req.method not in self._allowed_methods:
54
raise MethodNotAllowed(allowed=self._allowed_methods)
56
if req.method == 'GET':
57
outjson = self.GET(req)
58
# Since PATCH isn't yet an official HTTP method, we allow users to
59
# turn a PUT into a PATCH by supplying a special header.
60
elif req.method == 'PATCH' or (req.method == 'PUT' and
61
'X-IVLE-Patch-Semantics' in req.headers_in and
62
req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
64
input = cjson.decode(req.read())
65
except cjson.DecodeError:
66
raise BadRequest('Invalid JSON data')
67
outjson = self.PATCH(req, input)
68
elif req.method == 'PUT':
70
input = cjson.decode(req.read())
71
except cjson.DecodeError:
72
raise BadRequest('Invalid JSON data')
73
outjson = self.PUT(req, input)
74
# POST implies named operation.
75
elif req.method == 'POST':
76
# TODO: Check Content-Type and implement multipart/form-data.
77
opargs = dict(cgi.parse_qsl(req.read()))
79
opname = opargs['ivle.op']
82
raise BadRequest('No named operation specified.')
85
op = getattr(self, opname)
86
except AttributeError:
87
raise BadRequest('Invalid named operation.')
89
if not hasattr(op, '_rest_api_callable') or \
90
not op._rest_api_callable:
91
raise BadRequest('Invalid named operation.')
93
# Find any missing arguments, except for the first two (self, req)
94
(args, vaargs, varkw, defaults) = inspect.getargspec(op)
97
# To find missing arguments, we eliminate the provided arguments
98
# from the set of remaining function signature arguments. If the
99
# remaining signature arguments are in the args[-len(defaults):],
101
unspec = set(args) - set(opargs.keys())
102
if unspec and not defaults:
103
raise BadRequest('Missing arguments: ' + ', '.join(unspec))
105
unspec = [k for k in unspec if k not in args[-len(defaults):]]
108
raise BadRequest('Missing arguments: ' + ', '.join(unspec))
110
# We have extra arguments if the are no match args in the function
111
# signature, AND there is no **.
112
extra = set(opargs.keys()) - set(args)
113
if extra and not varkw:
114
raise BadRequest('Extra arguments: ' + ', '.join(extra))
116
outjson = op(req, **opargs)
118
req.content_type = self.content_type
119
if outjson is not None:
120
req.write(cjson.encode(outjson))
123
def named_operation(meth):
124
'''Declare a function to be accessible to HTTP users via the REST API.
126
meth._rest_api_callable = True