50
49
lambda self: [m for m in ('GET', 'PUT', 'PATCH')
51
50
if hasattr(self, m)] + ['POST'])
53
def authorize(self, req):
54
return True # Real authz performed in render().
56
def authorize_method(self, req, op):
57
if not hasattr(op, '_rest_api_permission'):
60
if (op._rest_api_permission not in
61
self.get_permissions(req.user, req.config)):
64
def convert_bool(self, value):
65
if value in ('True', 'true', True):
67
elif value in ('False', 'false', False):
72
52
def render(self, req):
73
53
if req.method not in self._allowed_methods:
74
54
raise MethodNotAllowed(allowed=self._allowed_methods)
76
56
if req.method == 'GET':
77
qargs = dict(cgi.parse_qsl(
78
urlparse.urlparse(req.unparsed_uri).query,
80
if 'ivle.op' in qargs:
81
outjson = self._named_operation(req, qargs, readonly=True)
83
self.authorize_method(req, self.GET)
84
outjson = self.GET(req)
57
outjson = self.GET(req)
85
58
# Since PATCH isn't yet an official HTTP method, we allow users to
86
59
# turn a PUT into a PATCH by supplying a special header.
87
60
elif req.method == 'PATCH' or (req.method == 'PUT' and
88
61
'X-IVLE-Patch-Semantics' in req.headers_in and
89
62
req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
90
self.authorize_method(req, self.PATCH)
92
64
input = cjson.decode(req.read())
93
65
except cjson.DecodeError:
94
66
raise BadRequest('Invalid JSON data')
95
67
outjson = self.PATCH(req, input)
96
68
elif req.method == 'PUT':
97
self.authorize_method(req, self.PUT)
99
70
input = cjson.decode(req.read())
100
71
except cjson.DecodeError:
103
74
# POST implies named operation.
104
75
elif req.method == 'POST':
105
76
# TODO: Check Content-Type and implement multipart/form-data.
107
opargs = dict(cgi.parse_qsl(data, keep_blank_values=1))
108
outjson = self._named_operation(req, opargs)
77
opargs = dict(cgi.parse_qsl(req.read()))
79
opname = opargs['ivle.op']
82
raise BadRequest('No named operation specified.')
85
op = getattr(self, opname)
86
except AttributeError:
87
raise BadRequest('Invalid named operation.')
89
if not hasattr(op, '_rest_api_callable') or \
90
not op._rest_api_callable:
91
raise BadRequest('Invalid named operation.')
93
# Find any missing arguments, except for the first two (self, req)
94
(args, vaargs, varkw, defaults) = inspect.getargspec(op)
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):],
101
unspec = set(args) - set(opargs.keys())
102
if unspec and not defaults:
103
raise BadRequest('Missing arguments: ' + ', '.join(unspec))
105
unspec = [k for k in unspec if k not in args[-len(defaults):]]
108
raise BadRequest('Missing arguments: ' + ', '.join(unspec))
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))
116
outjson = op(req, **opargs)
110
118
req.content_type = self.content_type
111
self.write_json(req, outjson)
113
#This is a separate function to allow additional data to be passed through
114
def write_json(self, req, outjson):
115
119
if outjson is not None:
116
120
req.write(cjson.encode(outjson))
119
def _named_operation(self, req, opargs, readonly=False):
121
opname = opargs['ivle.op']
122
del opargs['ivle.op']
124
raise BadRequest('No named operation specified.')
127
op = getattr(self, opname)
128
except AttributeError:
129
raise BadRequest('Invalid named operation.')
131
if not hasattr(op, '_rest_api_callable') or \
132
not op._rest_api_callable:
133
raise BadRequest('Invalid named operation.')
135
if readonly and op._rest_api_write_operation:
136
raise BadRequest('POST required for write operation.')
138
self.authorize_method(req, op)
140
# Find any missing arguments, except for the first two (self, req)
141
(args, vaargs, varkw, defaults) = inspect.getargspec(op)
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):],
148
unspec = set(args) - set(opargs.keys())
149
if unspec and not defaults:
150
raise BadRequest('Missing arguments: ' + ', '.join(unspec))
152
unspec = [k for k in unspec if k not in args[-len(defaults):]]
155
raise BadRequest('Missing arguments: ' + ', '.join(unspec))
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))
163
return op(req, **opargs)
166
class XHTMLRESTView(GenshiLoaderMixin, JSONRESTView):
167
"""A special type of RESTView which takes enhances the standard JSON
168
with genshi XHTML functions.
170
XHTMLRESTViews should have a template, which is rendered using their
171
context. This is returned in the JSON as 'html'"""
173
ctx = genshi.template.Context()
175
def render_fragment(self):
176
if self.template is None:
177
raise NotImplementedError()
179
rest_template = os.path.join(os.path.dirname(
180
inspect.getmodule(self).__file__), self.template)
181
tmpl = self._loader.load(rest_template)
183
return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml')
185
# This renders the template and adds it to the json
186
def write_json(self, req, outjson):
187
outjson["html"] = self.render_fragment()
188
req.write(cjson.encode(outjson))
191
class _named_operation(object):
123
def named_operation(meth):
192
124
'''Declare a function to be accessible to HTTP users via the REST API.
194
def __init__(self, write_operation, permission):
195
self.write_operation = write_operation
196
self.permission = permission
198
def __call__(self, func):
199
func._rest_api_callable = True
200
func._rest_api_write_operation = self.write_operation
201
func._rest_api_permission = self.permission
204
write_operation = functools.partial(_named_operation, True)
205
read_operation = functools.partial(_named_operation, False)
207
class require_permission(object):
208
'''Declare the permission required for use of a method via the REST API.
210
def __init__(self, permission):
211
self.permission = permission
213
def __call__(self, func):
214
func._rest_api_permission = self.permission
126
meth._rest_api_callable = True