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
18
# Author: Matt Giuca, Will Grant
18
# Author: Matt Giuca, Will Grant, Nick Chadwick
26
import genshi.template
25
28
from ivle.webapp.base.views import BaseView
26
29
from ivle.webapp.errors import BadRequest, MethodNotAllowed, Unauthorized
59
62
if op._rest_api_permission not in self.get_permissions(req.user):
60
63
raise Unauthorized()
65
def convert_bool(self, value):
66
if value in ('True', 'true', True):
68
elif value in ('False', 'false', False):
62
73
def render(self, req):
63
74
if req.method not in self._allowed_methods:
87
98
# POST implies named operation.
88
99
elif req.method == 'POST':
89
100
# TODO: Check Content-Type and implement multipart/form-data.
90
opargs = dict(cgi.parse_qsl(req.read()))
102
opargs = dict(cgi.parse_qsl(data, keep_blank_values=1))
92
104
opname = opargs['ivle.op']
93
105
del opargs['ivle.op']
131
143
outjson = op(req, **opargs)
133
145
req.content_type = self.content_type
146
self.write_json(req, outjson)
148
#This is a separate function to allow additional data to be passed through
149
def write_json(self, req, outjson):
134
150
if outjson is not None:
135
151
req.write(cjson.encode(outjson))
155
class XHTMLRESTView(JSONRESTView):
156
"""A special type of RESTView which takes enhances the standard JSON
157
with genshi XHTML functions.
159
XHTMLRESTViews should have a template, which is rendered using their
160
context. This is returned in the JSON as 'html'"""
162
ctx = genshi.template.Context()
164
def __init__(self, req, *args, **kwargs):
166
setattr(self, key, kwargs[key])
168
def render_fragment(self):
169
if self.template is None:
170
raise NotImplementedError()
172
rest_template = os.path.join(os.path.dirname(
173
inspect.getmodule(self).__file__), self.template)
174
loader = genshi.template.TemplateLoader(".", auto_reload=True)
175
tmpl = loader.load(rest_template)
177
return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml')
179
# This renders the template and adds it to the json
180
def write_json(self, req, outjson):
181
outjson["html"] = self.render_fragment()
182
req.write(cjson.encode(outjson))
138
185
class named_operation(object):
139
186
'''Declare a function to be accessible to HTTP users via the REST API.