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

« back to all changes in this revision

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

  • Committer: apeel
  • Date: 2008-03-14 01:33:50 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:688
setup.py now creates the /etc/init.d script for usrmgr-server, and install_proc.txt has instructions on installing it.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE - Informatics Virtual Learning Environment
2
 
# Copyright (C) 2007-2009 The University of Melbourne
3
 
#
4
 
# This program is free software; you can redistribute it and/or modify
5
 
# it under the terms of the GNU General Public License as published by
6
 
# the Free Software Foundation; either version 2 of the License, or
7
 
# (at your option) any later version.
8
 
#
9
 
# This program is distributed in the hope that it will be useful,
10
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 
# GNU General Public License for more details.
13
 
#
14
 
# You should have received a copy of the GNU General Public License
15
 
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
 
 
18
 
# Author: Matt Giuca, Will Grant
19
 
 
20
 
import cgi
21
 
import inspect
22
 
 
23
 
import cjson
24
 
 
25
 
from ivle.webapp.base.views import BaseView
26
 
from ivle.webapp.errors import BadRequest, MethodNotAllowed
27
 
 
28
 
class RESTView(BaseView):
29
 
    """
30
 
    A view which provides a RESTful interface. The content type is
31
 
    unspecified (see JSONRESTView for a specific content type).
32
 
    """
33
 
    content_type = "application/octet-stream"
34
 
 
35
 
    def __init__(self, req, *args, **kwargs):
36
 
        for key in kwargs:
37
 
            setattr(self, key, kwargs[key])
38
 
 
39
 
    def render(self, req):
40
 
        raise NotImplementedError()
41
 
 
42
 
class JSONRESTView(RESTView):
43
 
    """
44
 
    A special case of RESTView which deals entirely in JSON.
45
 
    """
46
 
    content_type = "application/json"
47
 
 
48
 
    _allowed_methods = property(
49
 
        lambda self: [m for m in ('GET', 'PUT', 'PATCH')
50
 
                      if hasattr(self, m)] + ['POST'])
51
 
 
52
 
    def render(self, req):
53
 
        if req.method not in self._allowed_methods:
54
 
            raise MethodNotAllowed(allowed=self._allowed_methods)
55
 
 
56
 
        if req.method == 'GET':
57
 
            outjson = self.GET(req)
58
 
        # Since PATCH isn't yet an official HTTP method, we allow users to
59
 
        # turn a PUT into a PATCH by supplying a special header.
60
 
        elif req.method == 'PATCH' or (req.method == 'PUT' and
61
 
              'X-IVLE-Patch-Semantics' in req.headers_in and
62
 
              req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
63
 
            try:
64
 
                input = cjson.decode(req.read())
65
 
            except cjson.DecodeError:
66
 
                raise BadRequest('Invalid JSON data')
67
 
            outjson = self.PATCH(req, input)
68
 
        elif req.method == 'PUT':
69
 
            try:
70
 
                input = cjson.decode(req.read())
71
 
            except cjson.DecodeError:
72
 
                raise BadRequest('Invalid JSON data')
73
 
            outjson = self.PUT(req, input)
74
 
        # POST implies named operation.
75
 
        elif req.method == 'POST':
76
 
            # TODO: Check Content-Type and implement multipart/form-data.
77
 
            opargs = dict(cgi.parse_qsl(req.read()))
78
 
            try:
79
 
                opname = opargs['ivle.op']
80
 
                del opargs['ivle.op']
81
 
            except KeyError:
82
 
                raise BadRequest('No named operation specified.')
83
 
 
84
 
            try:
85
 
                op = getattr(self, opname)
86
 
            except AttributeError:
87
 
                raise BadRequest('Invalid named operation.')
88
 
 
89
 
            if not hasattr(op, '_rest_api_callable') or \
90
 
               not op._rest_api_callable:
91
 
                raise BadRequest('Invalid named operation.')
92
 
 
93
 
            # Find any missing arguments, except for the first two (self, req)
94
 
            (args, vaargs, varkw, defaults) = inspect.getargspec(op)
95
 
            args = args[2:]
96
 
 
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):],
100
 
            # we are OK.
101
 
            unspec = set(args) - set(opargs.keys())
102
 
            if unspec and not defaults:
103
 
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
104
 
 
105
 
            unspec = [k for k in unspec if k not in args[-len(defaults):]]
106
 
 
107
 
            if unspec:
108
 
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
109
 
 
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))
115
 
 
116
 
            outjson = op(req, **opargs)
117
 
 
118
 
        req.content_type = self.content_type
119
 
        if outjson is not None:
120
 
            req.write(cjson.encode(outjson))
121
 
            req.write("\n")
122
 
 
123
 
def named_operation(meth):
124
 
    '''Declare a function to be accessible to HTTP users via the REST API.
125
 
    '''
126
 
    meth._rest_api_callable = True
127
 
    return meth
128