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

« back to all changes in this revision

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

  • Committer: Nick Chadwick
  • Date: 2009-02-24 03:32:59 UTC
  • mto: (1099.1.227 exercise-ui)
  • mto: This revision was merged to the branch mainline in revision 1162.
  • Revision ID: chadnickbok@gmail.com-20090224033259-m518nuqp6w9f23ax
Added a new page to display exercises. This will then be modified to
actually edit exercises.

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# along with this program; if not, write to the Free Software
16
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
17
 
18
 
# Author: Matt Giuca, Will Grant, Nick Chadwick
 
18
# Author: Matt Giuca, Will Grant
19
19
 
20
20
import cgi
21
 
import functools
 
21
import urlparse
22
22
import inspect
23
 
import os
24
 
import urlparse
25
 
 
26
 
try:
27
 
    import json
28
 
except ImportError:
29
 
    import simplejson as json
30
 
 
31
 
import genshi.template
 
23
 
 
24
import cjson
32
25
 
33
26
from ivle.webapp.base.views import BaseView
34
 
from ivle.webapp.base.xhtml import GenshiLoaderMixin
35
27
from ivle.webapp.errors import BadRequest, MethodNotAllowed, Unauthorized
36
28
 
37
29
class RESTView(BaseView):
41
33
    """
42
34
    content_type = "application/octet-stream"
43
35
 
 
36
    def __init__(self, req, *args, **kwargs):
 
37
        for key in kwargs:
 
38
            setattr(self, key, kwargs[key])
 
39
 
44
40
    def render(self, req):
45
41
        raise NotImplementedError()
46
42
 
61
57
        if not hasattr(op, '_rest_api_permission'):
62
58
            raise Unauthorized()
63
59
 
64
 
        if (op._rest_api_permission not in
65
 
            self.get_permissions(req.user, req.config)):
 
60
        if op._rest_api_permission not in self.get_permissions(req.user):
66
61
            raise Unauthorized()
67
62
    
68
63
    def convert_bool(self, value):
78
73
            raise MethodNotAllowed(allowed=self._allowed_methods)
79
74
 
80
75
        if req.method == 'GET':
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)
 
76
            self.authorize_method(req, self.GET)
 
77
            outjson = self.GET(req)
89
78
        # Since PATCH isn't yet an official HTTP method, we allow users to
90
79
        # turn a PUT into a PATCH by supplying a special header.
91
80
        elif req.method == 'PATCH' or (req.method == 'PUT' and
93
82
              req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
94
83
            self.authorize_method(req, self.PATCH)
95
84
            try:
96
 
                input = json.loads(req.read())
97
 
            except ValueError:
 
85
                input = cjson.decode(req.read())
 
86
            except cjson.DecodeError:
98
87
                raise BadRequest('Invalid JSON data')
99
88
            outjson = self.PATCH(req, input)
100
89
        elif req.method == 'PUT':
101
90
            self.authorize_method(req, self.PUT)
102
91
            try:
103
 
                input = json.loads(req.read())
104
 
            except ValueError:
 
92
                input = cjson.decode(req.read())
 
93
            except cjson.DecodeError:
105
94
                raise BadRequest('Invalid JSON data')
106
95
            outjson = self.PUT(req, input)
107
96
        # POST implies named operation.
109
98
            # TODO: Check Content-Type and implement multipart/form-data.
110
99
            data = req.read()
111
100
            opargs = dict(cgi.parse_qsl(data, keep_blank_values=1))
112
 
            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)
113
142
 
114
143
        req.content_type = self.content_type
115
 
        self.write_json(req, outjson)
116
 
 
117
 
    #This is a separate function to allow additional data to be passed through
118
 
    def write_json(self, req, outjson):
119
144
        if outjson is not None:
120
 
            req.write(json.dumps(outjson))
 
145
            req.write(cjson.encode(outjson))
121
146
            req.write("\n")
122
147
 
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):
171
 
    """A special type of RESTView which takes enhances the standard JSON
172
 
    with genshi XHTML functions.
173
 
    
174
 
    XHTMLRESTViews should have a template, which is rendered using their
175
 
    context. This is returned in the JSON as 'html'"""
176
 
    template = None
177
 
    ctx = genshi.template.Context()
178
 
 
179
 
    def render_fragment(self):
180
 
        if self.template is None:
181
 
            raise NotImplementedError()
182
 
 
183
 
        rest_template = os.path.join(os.path.dirname(
184
 
                inspect.getmodule(self).__file__), self.template)
185
 
        tmpl = self._loader.load(rest_template)
186
 
 
187
 
        return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml')
188
 
    
189
 
    # This renders the template and adds it to the json
190
 
    def write_json(self, req, outjson):
191
 
        outjson["html"] = self.render_fragment()
192
 
        req.write(json.dumps(outjson))
193
 
        req.write("\n")
194
 
 
195
 
class _named_operation(object):
 
148
class named_operation(object):
196
149
    '''Declare a function to be accessible to HTTP users via the REST API.
197
150
    '''
198
 
    def __init__(self, write_operation, permission):
199
 
        self.write_operation = write_operation
 
151
    def __init__(self, permission):
200
152
        self.permission = permission
201
153
 
202
154
    def __call__(self, func):
203
155
        func._rest_api_callable = True
204
 
        func._rest_api_write_operation = self.write_operation
205
156
        func._rest_api_permission = self.permission
206
157
        return func
207
158
 
208
 
write_operation = functools.partial(_named_operation, True)
209
 
read_operation = functools.partial(_named_operation, False)
210
 
 
211
159
class require_permission(object):
212
160
    '''Declare the permission required for use of a method via the REST API.
213
161
    '''
217
165
    def __call__(self, func):
218
166
        func._rest_api_permission = self.permission
219
167
        return func
 
168