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

« back to all changes in this revision

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

Merged my changes with those of Will's up-to-date branch.

I will now branch these changes to allow for a merge proposal to go
ahead without me poisoning it with new code.

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
import inspect
23
23
 
24
24
import cjson
 
25
import genshi.template
25
26
 
26
27
from ivle.webapp.base.views import BaseView
27
28
from ivle.webapp.errors import BadRequest, MethodNotAllowed, Unauthorized
141
142
            outjson = op(req, **opargs)
142
143
 
143
144
        req.content_type = self.content_type
 
145
        self.write_json(req, outjson)
 
146
 
 
147
    #This is a separate function to allow additional data to be passed through
 
148
    def write_json(self, req, outjson):
144
149
        if outjson is not None:
145
150
            req.write(cjson.encode(outjson))
146
151
            req.write("\n")
147
152
 
 
153
 
 
154
class XHTMLRESTView(JSONRESTView):
 
155
    """A special type of RESTView which takes enhances the standard JSON
 
156
    with genshi XHTML functions.
 
157
    
 
158
    XHTMLRESTViews should have a template, which is rendered using their
 
159
    context. This is returned in the JSON as 'html'"""
 
160
    template = None
 
161
    ctx = genshi.template.Context()
 
162
 
 
163
    def __init__(self, req, *args, **kwargs):
 
164
        for key in kwargs:
 
165
            setattr(self, key, kwargs[key])
 
166
    
 
167
    def render_fragment(self):
 
168
        if self.template is None:
 
169
            raise NotImplementedError()
 
170
 
 
171
        return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml')
 
172
    
 
173
    # This renders the template and adds it to the json
 
174
    def write_json(self, req, outjson):
 
175
        outjson["html"] = self.render_fragment()
 
176
        req.write(cjson.encode(outjson))
 
177
        req.write("\n")
 
178
 
148
179
class named_operation(object):
149
180
    '''Declare a function to be accessible to HTTP users via the REST API.
150
181
    '''
165
196
    def __call__(self, func):
166
197
        func._rest_api_permission = self.permission
167
198
        return func
168