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

« back to all changes in this revision

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

ivle.webapp.testing: Add, with fake request and user.
ivle.webapp.base.test: Add! Test the JSONRESTView, using the new mocks.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
# Author: Matt Giuca, Will Grant
19
19
 
 
20
import cjson
 
21
 
 
22
from ivle.webapp.errors import BadRequest
 
23
 
20
24
class BaseView(object):
21
25
    """
22
26
    Abstract base class for all view objects.
23
27
    """
24
 
 
25
 
    subpath_allowed = False
26
 
    offsite_posts_allowed = False
27
 
 
28
 
    def __init__(self, req, context, subpath=None):
29
 
        self.req = req
30
 
        self.context = context
31
 
        if self.subpath_allowed:
32
 
            self.subpath = subpath
33
 
 
34
 
    def render(self, req):
35
 
        raise NotImplementedError()
36
 
 
37
 
    def get_permissions(self, user, config):
38
 
        return self.context.get_permissions(user, config)
39
 
 
40
 
    def authorize(self, req):
41
 
        self.perms = self.get_permissions(req.user, req.config)
42
 
 
43
 
        return self.permission is None or self.permission in self.perms
 
28
    def __init__(self, req, **kwargs):
 
29
        pass
 
30
    def render(self, req):
 
31
        pass
 
32
 
 
33
class RESTView(BaseView):
 
34
    """
 
35
    A view which provides a RESTful interface. The content type is
 
36
    unspecified (see JSONRESTView for a specific content type).
 
37
    """
 
38
    content_type = "application/octet-stream"
 
39
 
 
40
    def __init__(self, req, *args, **kwargs):
 
41
        pass
 
42
 
 
43
    def render(self, req):
 
44
        if req.method == 'GET':
 
45
            outstr = self.GET(req)
 
46
        # XXX PATCH hack
 
47
        if req.method == 'PUT':
 
48
            outstr = self.PATCH(req, req.read())
 
49
        req.content_type = self.content_type
 
50
        req.write(outstr)
 
51
 
 
52
class JSONRESTView(RESTView):
 
53
    """
 
54
    A special case of RESTView which deals entirely in JSON.
 
55
    """
 
56
    content_type = "application/json"
 
57
 
 
58
    def render(self, req):
 
59
        if req.method == 'GET':
 
60
            outjson = self.GET(req)
 
61
        elif req.method == 'PATCH' or (req.method == 'PUT' and
 
62
              'X-IVLE-Patch-Semantics' in req.headers_in and
 
63
              req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
 
64
            outjson = self.PATCH(req, cjson.decode(req.read()))
 
65
        elif req.method == 'PUT':
 
66
            outjson = self.PUT(req, cjson.decode(req.read()))
 
67
        else:
 
68
            raise BadRequest
 
69
        req.content_type = self.content_type
 
70
        if outjson is not None:
 
71
            req.write(cjson.encode(outjson))
 
72
            req.write("\n")