~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/webapp/base/rest.py

Fixed a slight issue in the indentation of xhtml.py

Added a constructor in rest.py which means by default,
the behaviour of kwargs is consistent across all views

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
18
# Author: Matt Giuca, Will Grant
 
19
 
 
20
import cgi
 
21
import inspect
 
22
 
 
23
import cjson
 
24
 
 
25
from ivle.webapp.base.views import BaseView
 
26
from ivle.webapp.errors import BadRequest, MethodNotAllowed
 
27
 
 
28
class RESTView(BaseView):
 
29
    """
 
30
    A view which provides a RESTful interface. The content type is
 
31
    unspecified (see JSONRESTView for a specific content type).
 
32
    """
 
33
    content_type = "application/octet-stream"
 
34
 
 
35
    def __init__(self, req, *args, **kwargs):
 
36
        for key in kwargs:
 
37
            setattr(self, key, kwargs[key])
 
38
 
 
39
    def render(self, req):
 
40
        if req.method == 'GET':
 
41
            outstr = self.GET(req)
 
42
        # XXX PATCH hack
 
43
        if req.method == 'PUT':
 
44
            outstr = self.PATCH(req, req.read())
 
45
        req.content_type = self.content_type
 
46
        req.write(outstr)
 
47
 
 
48
class JSONRESTView(RESTView):
 
49
    """
 
50
    A special case of RESTView which deals entirely in JSON.
 
51
    """
 
52
    content_type = "application/json"
 
53
 
 
54
    _allowed_methods = property(
 
55
        lambda self: [m for m in ('GET', 'PUT', 'PATCH')
 
56
                      if hasattr(self, m)] + ['POST'])
 
57
 
 
58
    def render(self, req):
 
59
        if req.method not in self._allowed_methods:
 
60
            raise MethodNotAllowed(allowed=self._allowed_methods)
 
61
 
 
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()))
 
76
            try:
 
77
                opname = opargs['ivle.op']
 
78
                del opargs['ivle.op']
 
79
            except KeyError:
 
80
                raise BadRequest('No named operation specified.')
 
81
 
 
82
            try:
 
83
                op = getattr(self, opname)
 
84
            except AttributeError:
 
85
                raise BadRequest('Invalid named operation.')
 
86
 
 
87
            if not hasattr(op, '_rest_api_callable') or \
 
88
               not op._rest_api_callable:
 
89
                raise BadRequest('Invalid named operation.')
 
90
 
 
91
            # Find any missing arguments, except for the first two (self, req)
 
92
            (args, vaargs, varkw, defaults) = inspect.getargspec(op)
 
93
            args = args[2:]
 
94
 
 
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):],
 
98
            # we are OK.
 
99
            unspec = set(args) - set(opargs.keys())
 
100
            if unspec and not defaults:
 
101
                raise BadRequest('Missing arguments: ' + ','.join(unspec))
 
102
 
 
103
            unspec = [k for k in unspec if k not in args[-len(defaults):]]
 
104
 
 
105
            if unspec:
 
106
                raise BadRequest('Missing arguments: ' + ','.join(unspec))
 
107
 
 
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))
 
113
 
 
114
            outjson = op(req, **opargs)
 
115
        else:
 
116
            raise AssertionError('Unknown method somehow got through.')
 
117
 
 
118
        req.content_type = self.content_type
 
119
        if outjson is not None:
 
120
            req.write(cjson.encode(outjson))
 
121
            req.write("\n")
 
122
 
 
123
def named_operation(meth):
 
124
    '''Declare a function to be accessible to HTTP users via the REST API.
 
125
    '''
 
126
    meth._rest_api_callable = True
 
127
    return meth
 
128