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
if req.method == 'GET':
41
outstr = self.GET(req)
43
if req.method == 'PUT':
44
outstr = self.PATCH(req, req.read())
45
req.content_type = self.content_type
48
class JSONRESTView(RESTView):
50
A special case of RESTView which deals entirely in JSON.
52
content_type = "application/json"
54
_allowed_methods = property(
55
lambda self: [m for m in ('GET', 'PUT', 'PATCH')
56
if hasattr(self, m)] + ['POST'])
58
def render(self, req):
59
if req.method not in self._allowed_methods:
60
raise MethodNotAllowed(allowed=self._allowed_methods)
62
if req.method == 'GET':
63
outjson = self.GET(req)
64
# Since PATCH isn't yet an official HTTP method, we allow users to
65
# turn a PUT into a PATCH by supplying a special header.
66
elif req.method == 'PATCH' or (req.method == 'PUT' and
67
'X-IVLE-Patch-Semantics' in req.headers_in and
68
req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
69
outjson = self.PATCH(req, cjson.decode(req.read()))
70
elif req.method == 'PUT':
71
outjson = self.PUT(req, cjson.decode(req.read()))
72
# POST implies named operation.
73
elif req.method == 'POST':
74
# TODO: Check Content-Type and implement multipart/form-data.
75
opargs = dict(cgi.parse_qsl(req.read()))
77
opname = opargs['ivle.op']
80
raise BadRequest('No named operation specified.')
83
op = getattr(self, opname)
84
except AttributeError:
85
raise BadRequest('Invalid named operation.')
87
if not hasattr(op, '_rest_api_callable') or \
88
not op._rest_api_callable:
89
raise BadRequest('Invalid named operation.')
91
# Find any missing arguments, except for the first two (self, req)
92
(args, vaargs, varkw, defaults) = inspect.getargspec(op)
95
# To find missing arguments, we eliminate the provided arguments
96
# from the set of remaining function signature arguments. If the
97
# remaining signature arguments are in the args[-len(defaults):],
99
unspec = set(args) - set(opargs.keys())
100
if unspec and not defaults:
101
raise BadRequest('Missing arguments: ' + ','.join(unspec))
103
unspec = [k for k in unspec if k not in args[-len(defaults):]]
106
raise BadRequest('Missing arguments: ' + ','.join(unspec))
108
# We have extra arguments if the are no match args in the function
109
# signature, AND there is no **.
110
extra = set(opargs.keys()) - set(args)
111
if extra and not varkw:
112
raise BadRequest('Extra arguments: ' + ', '.join(extra))
114
outjson = op(req, **opargs)
116
raise AssertionError('Unknown method somehow got through.')
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