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

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
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):
1099.1.46 by Nick Chadwick
Fixed a slight issue in the indentation of xhtml.py
36
        for key in kwargs:
37
            setattr(self, key, kwargs[key])
1099.1.34 by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was
38
39
    def render(self, req):
1099.1.52 by William Grant
ivle.webapp.base.rest#RESTView: Remove broken old render() - it should be
40
        raise NotImplementedError()
1099.1.34 by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was
41
42
class JSONRESTView(RESTView):
43
    """
44
    A special case of RESTView which deals entirely in JSON.
45
    """
46
    content_type = "application/json"
47
48
    _allowed_methods = property(
49
        lambda self: [m for m in ('GET', 'PUT', 'PATCH')
50
                      if hasattr(self, m)] + ['POST'])
51
52
    def render(self, req):
53
        if req.method not in self._allowed_methods:
54
            raise MethodNotAllowed(allowed=self._allowed_methods)
55
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'):
1099.1.53 by William Grant
ivle.webapp.base.rest#JSONRESTView: Check for bad JSON input, rather than
63
            try:
64
                input = cjson.decode(req.read())
65
            except cjson.DecodeError:
66
                raise BadRequest('Invalid JSON data')
67
            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
68
        elif req.method == 'PUT':
1099.1.53 by William Grant
ivle.webapp.base.rest#JSONRESTView: Check for bad JSON input, rather than
69
            try:
70
                input = cjson.decode(req.read())
71
            except cjson.DecodeError:
72
                raise BadRequest('Invalid JSON data')
73
            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
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()))
78
            try:
79
                opname = opargs['ivle.op']
80
                del opargs['ivle.op']
81
            except KeyError:
82
                raise BadRequest('No named operation specified.')
83
84
            try:
85
                op = getattr(self, opname)
86
            except AttributeError:
87
                raise BadRequest('Invalid named operation.')
88
89
            if not hasattr(op, '_rest_api_callable') or \
90
               not op._rest_api_callable:
91
                raise BadRequest('Invalid named operation.')
92
93
            # Find any missing arguments, except for the first two (self, req)
94
            (args, vaargs, varkw, defaults) = inspect.getargspec(op)
95
            args = args[2:]
96
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):],
100
            # we are OK.
101
            unspec = set(args) - set(opargs.keys())
102
            if unspec and not defaults:
1099.1.52 by William Grant
ivle.webapp.base.rest#RESTView: Remove broken old render() - it should be
103
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
1099.1.34 by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was
104
105
            unspec = [k for k in unspec if k not in args[-len(defaults):]]
106
107
            if unspec:
1099.1.52 by William Grant
ivle.webapp.base.rest#RESTView: Remove broken old render() - it should be
108
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
1099.1.34 by William Grant
Split up ivle.webapp.base.views into ivle.webapp.base.{rest,xhtml}, as it was
109
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))
115
116
            outjson = op(req, **opargs)
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