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

« back to all changes in this revision

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

  • Committer: William Grant
  • Date: 2012-06-28 01:52:02 UTC
  • Revision ID: me@williamgrant.id.au-20120628015202-f6ru7o367gt6nvgz
Hah

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 cgi
 
21
import functools
 
22
import inspect
20
23
import os
21
 
import cgi
22
24
import urlparse
23
 
import inspect
24
 
 
25
 
import cjson
 
25
 
 
26
try:
 
27
    import json
 
28
except ImportError:
 
29
    import simplejson as json
 
30
 
26
31
import genshi.template
27
32
 
28
33
from ivle.webapp.base.views import BaseView
 
34
from ivle.webapp.base.xhtml import GenshiLoaderMixin
29
35
from ivle.webapp.errors import BadRequest, MethodNotAllowed, Unauthorized
30
36
 
31
37
class RESTView(BaseView):
35
41
    """
36
42
    content_type = "application/octet-stream"
37
43
 
38
 
    def __init__(self, req, *args, **kwargs):
39
 
        for key in kwargs:
40
 
            setattr(self, key, kwargs[key])
41
 
 
42
44
    def render(self, req):
43
45
        raise NotImplementedError()
44
46
 
59
61
        if not hasattr(op, '_rest_api_permission'):
60
62
            raise Unauthorized()
61
63
 
62
 
        if op._rest_api_permission not in self.get_permissions(req.user):
 
64
        if (op._rest_api_permission not in
 
65
            self.get_permissions(req.user, req.config)):
63
66
            raise Unauthorized()
64
67
    
65
68
    def convert_bool(self, value):
75
78
            raise MethodNotAllowed(allowed=self._allowed_methods)
76
79
 
77
80
        if req.method == 'GET':
78
 
            self.authorize_method(req, self.GET)
79
 
            outjson = self.GET(req)
 
81
            qargs = dict(cgi.parse_qsl(
 
82
                urlparse.urlparse(req.unparsed_uri).query,
 
83
                keep_blank_values=1))
 
84
            if 'ivle.op' in qargs:
 
85
                outjson = self._named_operation(req, qargs, readonly=True)
 
86
            else:
 
87
                self.authorize_method(req, self.GET)
 
88
                outjson = self.GET(req)
80
89
        # Since PATCH isn't yet an official HTTP method, we allow users to
81
90
        # turn a PUT into a PATCH by supplying a special header.
82
91
        elif req.method == 'PATCH' or (req.method == 'PUT' and
84
93
              req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
85
94
            self.authorize_method(req, self.PATCH)
86
95
            try:
87
 
                input = cjson.decode(req.read())
88
 
            except cjson.DecodeError:
 
96
                input = json.loads(req.read())
 
97
            except ValueError:
89
98
                raise BadRequest('Invalid JSON data')
90
99
            outjson = self.PATCH(req, input)
91
100
        elif req.method == 'PUT':
92
101
            self.authorize_method(req, self.PUT)
93
102
            try:
94
 
                input = cjson.decode(req.read())
95
 
            except cjson.DecodeError:
 
103
                input = json.loads(req.read())
 
104
            except ValueError:
96
105
                raise BadRequest('Invalid JSON data')
97
106
            outjson = self.PUT(req, input)
98
107
        # POST implies named operation.
100
109
            # TODO: Check Content-Type and implement multipart/form-data.
101
110
            data = req.read()
102
111
            opargs = dict(cgi.parse_qsl(data, keep_blank_values=1))
103
 
            try:
104
 
                opname = opargs['ivle.op']
105
 
                del opargs['ivle.op']
106
 
            except KeyError:
107
 
                raise BadRequest('No named operation specified.')
108
 
 
109
 
            try:
110
 
                op = getattr(self, opname)
111
 
            except AttributeError:
112
 
                raise BadRequest('Invalid named operation.')
113
 
 
114
 
            if not hasattr(op, '_rest_api_callable') or \
115
 
               not op._rest_api_callable:
116
 
                raise BadRequest('Invalid named operation.')
117
 
 
118
 
            self.authorize_method(req, op)
119
 
 
120
 
            # Find any missing arguments, except for the first two (self, req)
121
 
            (args, vaargs, varkw, defaults) = inspect.getargspec(op)
122
 
            args = args[2:]
123
 
 
124
 
            # To find missing arguments, we eliminate the provided arguments
125
 
            # from the set of remaining function signature arguments. If the
126
 
            # remaining signature arguments are in the args[-len(defaults):],
127
 
            # we are OK.
128
 
            unspec = set(args) - set(opargs.keys())
129
 
            if unspec and not defaults:
130
 
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
131
 
 
132
 
            unspec = [k for k in unspec if k not in args[-len(defaults):]]
133
 
 
134
 
            if unspec:
135
 
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
136
 
 
137
 
            # We have extra arguments if the are no match args in the function
138
 
            # signature, AND there is no **.
139
 
            extra = set(opargs.keys()) - set(args)
140
 
            if extra and not varkw:
141
 
                raise BadRequest('Extra arguments: ' + ', '.join(extra))
142
 
 
143
 
            outjson = op(req, **opargs)
 
112
            outjson = self._named_operation(req, opargs)
144
113
 
145
114
        req.content_type = self.content_type
146
115
        self.write_json(req, outjson)
148
117
    #This is a separate function to allow additional data to be passed through
149
118
    def write_json(self, req, outjson):
150
119
        if outjson is not None:
151
 
            req.write(cjson.encode(outjson))
 
120
            req.write(json.dumps(outjson))
152
121
            req.write("\n")
153
122
 
154
 
 
155
 
class XHTMLRESTView(JSONRESTView):
 
123
    def _named_operation(self, req, opargs, readonly=False):
 
124
        try:
 
125
            opname = opargs['ivle.op']
 
126
            del opargs['ivle.op']
 
127
        except KeyError:
 
128
            raise BadRequest('No named operation specified.')
 
129
 
 
130
        try:
 
131
            op = getattr(self, opname)
 
132
        except AttributeError:
 
133
            raise BadRequest('Invalid named operation.')
 
134
 
 
135
        if not hasattr(op, '_rest_api_callable') or \
 
136
           not op._rest_api_callable:
 
137
            raise BadRequest('Invalid named operation.')
 
138
 
 
139
        if readonly and op._rest_api_write_operation:
 
140
            raise BadRequest('POST required for write operation.')
 
141
 
 
142
        self.authorize_method(req, op)
 
143
 
 
144
        # Find any missing arguments, except for the first two (self, req)
 
145
        (args, vaargs, varkw, defaults) = inspect.getargspec(op)
 
146
        args = args[2:]
 
147
 
 
148
        # To find missing arguments, we eliminate the provided arguments
 
149
        # from the set of remaining function signature arguments. If the
 
150
        # remaining signature arguments are in the args[-len(defaults):],
 
151
        # we are OK.
 
152
        unspec = set(args) - set(opargs.keys())
 
153
        if unspec and not defaults:
 
154
            raise BadRequest('Missing arguments: ' + ', '.join(unspec))
 
155
 
 
156
        unspec = [k for k in unspec if k not in args[-len(defaults):]]
 
157
 
 
158
        if unspec:
 
159
            raise BadRequest('Missing arguments: ' + ', '.join(unspec))
 
160
 
 
161
        # We have extra arguments if the are no match args in the function
 
162
        # signature, AND there is no **.
 
163
        extra = set(opargs.keys()) - set(args)
 
164
        if extra and not varkw:
 
165
            raise BadRequest('Extra arguments: ' + ', '.join(extra))
 
166
 
 
167
        return op(req, **opargs)
 
168
 
 
169
 
 
170
class XHTMLRESTView(GenshiLoaderMixin, JSONRESTView):
156
171
    """A special type of RESTView which takes enhances the standard JSON
157
172
    with genshi XHTML functions.
158
173
    
161
176
    template = None
162
177
    ctx = genshi.template.Context()
163
178
 
164
 
    def __init__(self, req, *args, **kwargs):
165
 
        for key in kwargs:
166
 
            setattr(self, key, kwargs[key])
167
 
    
168
179
    def render_fragment(self):
169
180
        if self.template is None:
170
181
            raise NotImplementedError()
171
182
 
172
183
        rest_template = os.path.join(os.path.dirname(
173
184
                inspect.getmodule(self).__file__), self.template)
174
 
        loader = genshi.template.TemplateLoader(".", auto_reload=True)
175
 
        tmpl = loader.load(rest_template)
 
185
        tmpl = self._loader.load(rest_template)
176
186
 
177
187
        return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml')
178
188
    
179
189
    # This renders the template and adds it to the json
180
190
    def write_json(self, req, outjson):
181
191
        outjson["html"] = self.render_fragment()
182
 
        req.write(cjson.encode(outjson))
 
192
        req.write(json.dumps(outjson))
183
193
        req.write("\n")
184
194
 
185
 
class named_operation(object):
 
195
class _named_operation(object):
186
196
    '''Declare a function to be accessible to HTTP users via the REST API.
187
197
    '''
188
 
    def __init__(self, permission):
 
198
    def __init__(self, write_operation, permission):
 
199
        self.write_operation = write_operation
189
200
        self.permission = permission
190
201
 
191
202
    def __call__(self, func):
192
203
        func._rest_api_callable = True
 
204
        func._rest_api_write_operation = self.write_operation
193
205
        func._rest_api_permission = self.permission
194
206
        return func
195
207
 
 
208
write_operation = functools.partial(_named_operation, True)
 
209
read_operation = functools.partial(_named_operation, False)
 
210
 
196
211
class require_permission(object):
197
212
    '''Declare the permission required for use of a method via the REST API.
198
213
    '''