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

« back to all changes in this revision

Viewing changes to lib/common/cgirequest.py

  • Committer: mattgiuca
  • Date: 2008-02-05 04:02:22 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:414
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
Request object compatible with the IVLE request object (and our app
handlers).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2008 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
# Module: cgirequest
 
19
# Author: Matt Giuca
 
20
# Date:   5/2/2007
 
21
 
 
22
# Presents a CGIRequest class which creates an object compatible with IVLE
 
23
# Request objects (the same interface exposed by www.dispatch.request) from a
 
24
# CGI script.
 
25
# This allows CGI scripts to create request objects and then pass them to
 
26
# normal IVLE handlers.
 
27
 
 
28
# NOTE: This object does not support write_html_head_foot (simply because we
 
29
# do not need it in its intended application: fileservice).
 
30
 
 
31
import sys
 
32
import os
 
33
import cgi
 
34
 
 
35
import conf
 
36
 
 
37
# Utility functions
 
38
 
 
39
def _http_headers_in_from_cgi():
 
40
    """Returns a dictionary of HTTP headers and their values, reading from the
 
41
    CGI environment."""
 
42
    d = {}
 
43
    for k in os.environ.keys():
 
44
        if k.startswith("HTTP_"):
 
45
            # Change the case - underscores become - and each word is
 
46
            # capitalised
 
47
            varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(),
 
48
                                k[5:].split('_')))
 
49
            d[varname] = os.environ[k]
 
50
    return d
 
51
 
 
52
class CGIRequest:
 
53
    """An IVLE request object, built from a CGI script. This is presented to
 
54
    the IVLE apps as a way of interacting with the CGI server.
 
55
    See dispatch.request for a full interface specification.
 
56
    """
 
57
 
 
58
    # COPIED from dispatch/request.py
 
59
    # Special code for an OK response.
 
60
    # Do not use HTTP_OK; for some reason Apache produces an "OK" error
 
61
    # message if you do that.
 
62
    OK  = 0
 
63
 
 
64
    # HTTP status codes
 
65
 
 
66
    HTTP_CONTINUE                     = 100
 
67
    HTTP_SWITCHING_PROTOCOLS          = 101
 
68
    HTTP_PROCESSING                   = 102
 
69
    HTTP_OK                           = 200
 
70
    HTTP_CREATED                      = 201
 
71
    HTTP_ACCEPTED                     = 202
 
72
    HTTP_NON_AUTHORITATIVE            = 203
 
73
    HTTP_NO_CONTENT                   = 204
 
74
    HTTP_RESET_CONTENT                = 205
 
75
    HTTP_PARTIAL_CONTENT              = 206
 
76
    HTTP_MULTI_STATUS                 = 207
 
77
    HTTP_MULTIPLE_CHOICES             = 300
 
78
    HTTP_MOVED_PERMANENTLY            = 301
 
79
    HTTP_MOVED_TEMPORARILY            = 302
 
80
    HTTP_SEE_OTHER                    = 303
 
81
    HTTP_NOT_MODIFIED                 = 304
 
82
    HTTP_USE_PROXY                    = 305
 
83
    HTTP_TEMPORARY_REDIRECT           = 307
 
84
    HTTP_BAD_REQUEST                  = 400
 
85
    HTTP_UNAUTHORIZED                 = 401
 
86
    HTTP_PAYMENT_REQUIRED             = 402
 
87
    HTTP_FORBIDDEN                    = 403
 
88
    HTTP_NOT_FOUND                    = 404
 
89
    HTTP_METHOD_NOT_ALLOWED           = 405
 
90
    HTTP_NOT_ACCEPTABLE               = 406
 
91
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
 
92
    HTTP_REQUEST_TIME_OUT             = 408
 
93
    HTTP_CONFLICT                     = 409
 
94
    HTTP_GONE                         = 410
 
95
    HTTP_LENGTH_REQUIRED              = 411
 
96
    HTTP_PRECONDITION_FAILED          = 412
 
97
    HTTP_REQUEST_ENTITY_TOO_LARGE     = 413
 
98
    HTTP_REQUEST_URI_TOO_LARGE        = 414
 
99
    HTTP_UNSUPPORTED_MEDIA_TYPE       = 415
 
100
    HTTP_RANGE_NOT_SATISFIABLE        = 416
 
101
    HTTP_EXPECTATION_FAILED           = 417
 
102
    HTTP_UNPROCESSABLE_ENTITY         = 422
 
103
    HTTP_LOCKED                       = 423
 
104
    HTTP_FAILED_DEPENDENCY            = 424
 
105
    HTTP_INTERNAL_SERVER_ERROR        = 500
 
106
    HTTP_NOT_IMPLEMENTED              = 501
 
107
    HTTP_BAD_GATEWAY                  = 502
 
108
    HTTP_SERVICE_UNAVAILABLE          = 503
 
109
    HTTP_GATEWAY_TIME_OUT             = 504
 
110
    HTTP_VERSION_NOT_SUPPORTED        = 505
 
111
    HTTP_VARIANT_ALSO_VARIES          = 506
 
112
    HTTP_INSUFFICIENT_STORAGE         = 507
 
113
    HTTP_NOT_EXTENDED                 = 510
 
114
 
 
115
    def __init__(self):
 
116
        """Builds an CGI Request object from the current CGI environment.
 
117
        This results in an object with all of the necessary methods and
 
118
        additional fields.
 
119
        """
 
120
        self.headers_written = False
 
121
 
 
122
        # Determine if the browser used the public host name to make the
 
123
        # request (in which case we are in "public mode")
 
124
        if os.environ['SERVER_NAME'] == conf.public_host:
 
125
            self.publicmode = True
 
126
        else:
 
127
            self.publicmode = False
 
128
 
 
129
        # Inherit values for the input members
 
130
        self.method = os.environ['REQUEST_METHOD']
 
131
        self.uri = os.environ['REQUEST_URI']
 
132
        # Split the given path into the app (top-level dir) and sub-path
 
133
        # (after first stripping away the root directory)
 
134
        path = common.util.unmake_path(self.uri)
 
135
        if self.publicmode:
 
136
            self.app = None
 
137
            self.path = path
 
138
        else:
 
139
            (self.app, self.path) = (common.util.split_path(path))
 
140
        self.username = None
 
141
        self.hostname = os.environ['SERVER_NAME']
 
142
        self.headers_in = _http_headers_in_from_cgi()
 
143
        self.headers_out = {}
 
144
 
 
145
        # Default values for the output members
 
146
        self.status = CGIRequest.HTTP_OK
 
147
        self.content_type = None        # Use Apache's default
 
148
        self.location = None
 
149
        self.title = None     # Will be set by dispatch before passing to app
 
150
        self.styles = []
 
151
        self.scripts = []
 
152
        self.write_html_head_foot = False
 
153
        self.got_common_vars = False
 
154
 
 
155
    def __writeheaders(self):
 
156
        """Writes out the HTTP and HTML headers before any real data is
 
157
        written."""
 
158
        self.headers_written = True
 
159
        if 'Content-Type' in self.headers_out:
 
160
            self.content_type = self.headers_out['Content-Type']
 
161
        if 'Location' in self.headers_out:
 
162
            self.location = self.headers_out['Location']
 
163
 
 
164
        # CGI allows for four response types: Document, Local Redirect, Client
 
165
        # Redirect, and Client Redirect w/ Document
 
166
        # XXX We do not allow Local Redirect
 
167
        if self.location != None:
 
168
            # This is a Client Redirect
 
169
            print "Location: %s" % self.location
 
170
            if self.content_type == None:
 
171
                # Just redirect
 
172
                return
 
173
            # Else: This is a Client Redirect with Document
 
174
            print "Status: %d" % self.status
 
175
            print "Content-Type: %s" % self.content_type
 
176
        else:
 
177
            # This is a Document response
 
178
            print "Content-Type: %s" % self.content_type
 
179
            print "Status: %d" % self.status
 
180
 
 
181
        # Print the other headers
 
182
        for k,v in self.headers_out.items():
 
183
            if k != 'Content-Type' and k != 'Location':
 
184
                print "%s: %s" % (k, v)
 
185
 
 
186
        # XXX write_html_head_foot not supported
 
187
        #if self.write_html_head_foot:
 
188
        #    # Write the HTML header, pass "self" (request object)
 
189
        #    self.func_write_html_head(self)
 
190
        # Print a blank line to signal the start of output
 
191
        print
 
192
 
 
193
    def ensure_headers_written(self):
 
194
        """Writes out the HTTP and HTML headers if they haven't already been
 
195
        written."""
 
196
        if not self.headers_written:
 
197
            self.__writeheaders()
 
198
 
 
199
    def write(self, string, flush=1):
 
200
        """Writes string directly to the client, then flushes the buffer,
 
201
        unless flush is 0."""
 
202
 
 
203
        if not self.headers_written:
 
204
            self.__writeheaders()
 
205
        if isinstance(string, unicode):
 
206
            # Encode unicode strings as UTF-8
 
207
            # (Otherwise cannot handle being written to a bytestream)
 
208
            sys.stdout.write(string.encode('utf8'))
 
209
        else:
 
210
            # 8-bit clean strings just get written directly.
 
211
            # This includes binary strings.
 
212
            sys.stdout.write(string)
 
213
 
 
214
    def flush(self):
 
215
        """Flushes the output buffer."""
 
216
        sys.stdout.flush()
 
217
 
 
218
    def sendfile(self, filename):
 
219
        """Sends the named file directly to the client."""
 
220
        if not self.headers_written:
 
221
            self.__writeheaders()
 
222
        f = open(filename)
 
223
        buf = f.read(1024)
 
224
        while len(buf) > 0:
 
225
            sys.stdout.flush(buf)
 
226
            buf = f.read(1024)
 
227
        f.close()
 
228
 
 
229
    def read(self, len=None):
 
230
        """Reads at most len bytes directly from the client. (See mod_python
 
231
        Request.read)."""
 
232
        if len is None:
 
233
            return sys.stdin.read()
 
234
        else:
 
235
            return sys.stdin.read(len)
 
236
 
 
237
    def throw_error(self, httpcode):
 
238
        """Writes out an HTTP error of the specified code. Exits the process,
 
239
        so any code following this call will not be executed.
 
240
 
 
241
        (This is justified because of the nature of CGI, it is a single-script
 
242
        environment, there is no containing process which needs to catch an
 
243
        exception).
 
244
 
 
245
        httpcode: An HTTP response status code. Pass a constant from the
 
246
        Request class.
 
247
        """
 
248
        self.status = httpcode
 
249
        self.content_type = "text/html"
 
250
        # Emulate an Apache error
 
251
        self.write("""<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
 
252
<html><head>
 
253
<title>%d Error</title>
 
254
</head><body>
 
255
<h1>Error</h1>
 
256
<p>A %d error was triggered by a CGI app.</p>
 
257
</body></html>
 
258
""" % (httpcode, httpcode))
 
259
        # Exit the process completely
 
260
        self.flush()
 
261
        sys.exit(httpcode)
 
262
 
 
263
    def throw_redirect(self, location):
 
264
        """Writes out an HTTP redirect to the specified URL. Exits the
 
265
        process, so any code following this call will not be executed.
 
266
 
 
267
        httpcode: An HTTP response status code. Pass a constant from the
 
268
        Request class.
 
269
        """
 
270
        self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
 
271
        self.location = location
 
272
        self.ensure_headers_written()
 
273
        self.flush()
 
274
        sys.exit(self.status)
 
275
 
 
276
    def get_session(self):
 
277
        """Returns a mod_python Session object for this request.
 
278
        Note that this is dependent on mod_python and may need to change
 
279
        interface if porting away from mod_python."""
 
280
        # Cache the session object
 
281
        if not hasattr(self, 'session'):
 
282
            #self.session = Session.FileSession(self.apache_req)
 
283
            self.session = None
 
284
            # FIXME: How to get session?
 
285
        return self.session
 
286
 
 
287
    def get_fieldstorage(self):
 
288
        """Returns a mod_python FieldStorage object for this request.
 
289
        Note that this is dependent on mod_python and may need to change
 
290
        interface if porting away from mod_python."""
 
291
        # Cache the fieldstorage object
 
292
        if not hasattr(self, 'fields'):
 
293
            self.fields = cgi.FieldStorage()
 
294
        return self.fields
 
295
 
 
296
    def get_cgi_environ(self):
 
297
        """Returns the CGI environment emulation for this request. (Calls
 
298
        add_common_vars). The environment is returned as a mapping
 
299
        compatible with os.environ."""
 
300
        return os.environ