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

« back to all changes in this revision

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

  • Committer: William Grant
  • Author(s): David Coles
  • Date: 2010-05-31 12:04:13 UTC
  • mto: This revision was merged to the branch mainline in revision 1825.
  • Revision ID: coles.david@gmail.com-20100531120413-4x8ufmzf9i25hybq
Editor: Migrate to CodeMirror. Syntax highlighting hardcoded to Python for the 
moment.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
# Author: Matt Giuca, Will Grant, Nick Chadwick
19
19
 
 
20
import os
20
21
import cgi
21
 
import functools
 
22
import urlparse
22
23
import inspect
23
 
import os
24
 
import urlparse
25
24
 
26
25
import cjson
27
26
import genshi.template
74
73
            raise MethodNotAllowed(allowed=self._allowed_methods)
75
74
 
76
75
        if req.method == 'GET':
77
 
            qargs = dict(cgi.parse_qsl(
78
 
                urlparse.urlparse(req.unparsed_uri).query,
79
 
                keep_blank_values=1))
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)
 
76
            self.authorize_method(req, self.GET)
 
77
            outjson = self.GET(req)
85
78
        # Since PATCH isn't yet an official HTTP method, we allow users to
86
79
        # turn a PUT into a PATCH by supplying a special header.
87
80
        elif req.method == 'PATCH' or (req.method == 'PUT' and
105
98
            # TODO: Check Content-Type and implement multipart/form-data.
106
99
            data = req.read()
107
100
            opargs = dict(cgi.parse_qsl(data, keep_blank_values=1))
108
 
            outjson = self._named_operation(req, opargs)
 
101
            try:
 
102
                opname = opargs['ivle.op']
 
103
                del opargs['ivle.op']
 
104
            except KeyError:
 
105
                raise BadRequest('No named operation specified.')
 
106
 
 
107
            try:
 
108
                op = getattr(self, opname)
 
109
            except AttributeError:
 
110
                raise BadRequest('Invalid named operation.')
 
111
 
 
112
            if not hasattr(op, '_rest_api_callable') or \
 
113
               not op._rest_api_callable:
 
114
                raise BadRequest('Invalid named operation.')
 
115
 
 
116
            self.authorize_method(req, op)
 
117
 
 
118
            # Find any missing arguments, except for the first two (self, req)
 
119
            (args, vaargs, varkw, defaults) = inspect.getargspec(op)
 
120
            args = args[2:]
 
121
 
 
122
            # To find missing arguments, we eliminate the provided arguments
 
123
            # from the set of remaining function signature arguments. If the
 
124
            # remaining signature arguments are in the args[-len(defaults):],
 
125
            # we are OK.
 
126
            unspec = set(args) - set(opargs.keys())
 
127
            if unspec and not defaults:
 
128
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
 
129
 
 
130
            unspec = [k for k in unspec if k not in args[-len(defaults):]]
 
131
 
 
132
            if unspec:
 
133
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
 
134
 
 
135
            # We have extra arguments if the are no match args in the function
 
136
            # signature, AND there is no **.
 
137
            extra = set(opargs.keys()) - set(args)
 
138
            if extra and not varkw:
 
139
                raise BadRequest('Extra arguments: ' + ', '.join(extra))
 
140
 
 
141
            outjson = op(req, **opargs)
109
142
 
110
143
        req.content_type = self.content_type
111
144
        self.write_json(req, outjson)
116
149
            req.write(cjson.encode(outjson))
117
150
            req.write("\n")
118
151
 
119
 
    def _named_operation(self, req, opargs, readonly=False):
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
 
 
135
 
        if readonly and op._rest_api_write_operation:
136
 
            raise BadRequest('POST required for write operation.')
137
 
 
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
 
 
165
152
 
166
153
class XHTMLRESTView(GenshiLoaderMixin, JSONRESTView):
167
154
    """A special type of RESTView which takes enhances the standard JSON
188
175
        req.write(cjson.encode(outjson))
189
176
        req.write("\n")
190
177
 
191
 
class _named_operation(object):
 
178
class named_operation(object):
192
179
    '''Declare a function to be accessible to HTTP users via the REST API.
193
180
    '''
194
 
    def __init__(self, write_operation, permission):
195
 
        self.write_operation = write_operation
 
181
    def __init__(self, permission):
196
182
        self.permission = permission
197
183
 
198
184
    def __call__(self, func):
199
185
        func._rest_api_callable = True
200
 
        func._rest_api_write_operation = self.write_operation
201
186
        func._rest_api_permission = self.permission
202
187
        return func
203
188
 
204
 
write_operation = functools.partial(_named_operation, True)
205
 
read_operation = functools.partial(_named_operation, False)
206
 
 
207
189
class require_permission(object):
208
190
    '''Declare the permission required for use of a method via the REST API.
209
191
    '''