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

« back to all changes in this revision

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

  • Committer: Matt Giuca
  • Date: 2010-07-20 09:42:45 UTC
  • Revision ID: matt.giuca@gmail.com-20100720094245-0poipwrxm9tde8et
TextView: Removed constructor (it just called its superclass ctor).

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
 
25
26
import cjson
26
27
import genshi.template
27
28
 
28
29
from ivle.webapp.base.views import BaseView
 
30
from ivle.webapp.base.xhtml import GenshiLoaderMixin
29
31
from ivle.webapp.errors import BadRequest, MethodNotAllowed, Unauthorized
30
32
 
31
33
class RESTView(BaseView):
35
37
    """
36
38
    content_type = "application/octet-stream"
37
39
 
38
 
    def __init__(self, req, *args, **kwargs):
39
 
        for key in kwargs:
40
 
            setattr(self, key, kwargs[key])
41
 
 
42
40
    def render(self, req):
43
41
        raise NotImplementedError()
44
42
 
59
57
        if not hasattr(op, '_rest_api_permission'):
60
58
            raise Unauthorized()
61
59
 
62
 
        if op._rest_api_permission not in self.get_permissions(req.user):
 
60
        if (op._rest_api_permission not in
 
61
            self.get_permissions(req.user, req.config)):
63
62
            raise Unauthorized()
64
63
    
65
64
    def convert_bool(self, value):
75
74
            raise MethodNotAllowed(allowed=self._allowed_methods)
76
75
 
77
76
        if req.method == 'GET':
78
 
            self.authorize_method(req, self.GET)
79
 
            outjson = self.GET(req)
 
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)
80
85
        # Since PATCH isn't yet an official HTTP method, we allow users to
81
86
        # turn a PUT into a PATCH by supplying a special header.
82
87
        elif req.method == 'PATCH' or (req.method == 'PUT' and
100
105
            # TODO: Check Content-Type and implement multipart/form-data.
101
106
            data = req.read()
102
107
            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)
 
108
            outjson = self._named_operation(req, opargs)
144
109
 
145
110
        req.content_type = self.content_type
146
111
        self.write_json(req, outjson)
151
116
            req.write(cjson.encode(outjson))
152
117
            req.write("\n")
153
118
 
154
 
 
155
 
class XHTMLRESTView(JSONRESTView):
 
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
 
 
166
class XHTMLRESTView(GenshiLoaderMixin, JSONRESTView):
156
167
    """A special type of RESTView which takes enhances the standard JSON
157
168
    with genshi XHTML functions.
158
169
    
161
172
    template = None
162
173
    ctx = genshi.template.Context()
163
174
 
164
 
    def __init__(self, req, *args, **kwargs):
165
 
        for key in kwargs:
166
 
            setattr(self, key, kwargs[key])
167
 
    
168
175
    def render_fragment(self):
169
176
        if self.template is None:
170
177
            raise NotImplementedError()
171
178
 
172
179
        rest_template = os.path.join(os.path.dirname(
173
180
                inspect.getmodule(self).__file__), self.template)
174
 
        loader = genshi.template.TemplateLoader(".", auto_reload=True)
175
 
        tmpl = loader.load(rest_template)
 
181
        tmpl = self._loader.load(rest_template)
176
182
 
177
183
        return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml')
178
184
    
182
188
        req.write(cjson.encode(outjson))
183
189
        req.write("\n")
184
190
 
185
 
class named_operation(object):
 
191
class _named_operation(object):
186
192
    '''Declare a function to be accessible to HTTP users via the REST API.
187
193
    '''
188
 
    def __init__(self, permission):
 
194
    def __init__(self, write_operation, permission):
 
195
        self.write_operation = write_operation
189
196
        self.permission = permission
190
197
 
191
198
    def __call__(self, func):
192
199
        func._rest_api_callable = True
 
200
        func._rest_api_write_operation = self.write_operation
193
201
        func._rest_api_permission = self.permission
194
202
        return func
195
203
 
 
204
write_operation = functools.partial(_named_operation, True)
 
205
read_operation = functools.partial(_named_operation, False)
 
206
 
196
207
class require_permission(object):
197
208
    '''Declare the permission required for use of a method via the REST API.
198
209
    '''