Ticket #2407: CGI.2.py

File CGI.2.py, 6.8 KB (added by Martin, 18 years ago)

The CGI Handler classes (replaces the old CGI.py which had still my standard file-header)

Line 
1import django
2import sys
3from django import http
4from django.core.handlers.base import BaseHandler
5from django.core import signals
6from django.dispatch import dispatcher
7from django.utils import datastructures
8
9__all__ = ["CGI_Handler"]
10
11# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
12STATUS_CODE_TEXT = \
13 { 100 : "CONTINUE"
14 , 101 : "SWITCHING PROTOCOLS"
15 , 200 : "OK"
16 , 201 : "CREATED"
17 , 202 : "ACCEPTED"
18 , 203 : "NON-AUTHORITATIVE INFORMATION"
19 , 204 : "NO CONTENT"
20 , 205 : "RESET CONTENT"
21 , 206 : "PARTIAL CONTENT"
22 , 300 : "MULTIPLE CHOICES"
23 , 301 : "MOVED PERMANENTLY"
24 , 302 : "FOUND"
25 , 303 : "SEE OTHER"
26 , 304 : "NOT MODIFIED"
27 , 305 : "USE PROXY"
28 , 306 : "RESERVED"
29 , 307 : "TEMPORARY REDIRECT"
30 , 400 : "BAD REQUEST"
31 , 401 : "UNAUTHORIZED"
32 , 402 : "PAYMENT REQUIRED"
33 , 403 : "FORBIDDEN"
34 , 404 : "NOT FOUND"
35 , 405 : "METHOD NOT ALLOWED"
36 , 406 : "NOT ACCEPTABLE"
37 , 407 : "PROXY AUTHENTICATION REQUIRED"
38 , 408 : "REQUEST TIMEOUT"
39 , 409 : "CONFLICT"
40 , 410 : "GONE"
41 , 411 : "LENGTH REQUIRED"
42 , 412 : "PRECONDITION FAILED"
43 , 413 : "REQUEST ENTITY TOO LARGE"
44 , 414 : "REQUEST-URI TOO LONG"
45 , 415 : "UNSUPPORTED MEDIA TYPE"
46 , 416 : "REQUESTED RANGE NOT SATISFIABLE"
47 , 417 : "EXPECTATION FAILED"
48 , 500 : "INTERNAL SERVER ERROR"
49 , 501 : "NOT IMPLEMENTED"
50 , 502 : "BAD GATEWAY"
51 , 503 : "SERVICE UNAVAILABLE"
52 , 504 : "GATEWAY TIMEOUT"
53 , 505 : "HTTP VERSION NOT SUPPORTED"
54 }
55
56class CGI_Request (http.HttpRequest) :
57 """A Request from a normal CGI interface."""
58
59 _request = None
60 _get = None
61 _post = None
62 _cookies = None
63 _files = None
64
65 def __init__ (self, environ) :
66 ### don't chain up, we set the dict's here as properties
67 ### super (CGI_Request, self).__init__ (self, environ)
68 self.environ = environ
69 self.path = environ.get ("REDIRECT_URL", "/")
70 self.META = environ
71 self.method = environ.get ("REQUEST_METHOD", "GET").upper()
72 # end def __init__
73
74 def __repr__(self):
75 return "\n".join \
76 ( ( "<%s" % (self.__class__.__name__)
77 , " GET: %r" % (self.GET)
78 , " POST: %r" % (self.POST)
79 , " COOKIES: %r" % (self.COOKIES)
80 , " META: %r" % (self.META)
81 , ">"
82 )
83 )
84 # end def __repr__
85
86 def get_full_path(self):
87 return '%s%s' % \
88 ( self.path
89 , self.environ.get ("QUERY_STRING", "")
90 and ("?" + self.environ ["QUERY_STRING"])
91 or ''
92 )
93 # end def get_full_path
94
95 def _load_post_and_files(self):
96 # Populates self._post and self._files
97 if self.method == "POST" :
98 if self.environ.get ("CONTENT_TYPE", "").startswith ("multipart") :
99 header_dict = dict\
100 ( [ (k, v) for k, v in self.environ.iteritems ()
101 if k.startswith('HTTP_')
102 ]
103 )
104 header_dict ["Content-Type"] = self.environ.get \
105 ("CONTENT_TYPE", "")
106 (self._post, self._files
107 ) = http.parse_file_upload (header_dict, self.raw_post_data)
108 else :
109 self._post = http.QueryDict (self.raw_post_data)
110 self._files = datastructures.MultiValueDict ()
111 else:
112 self._post = http.QueryDict ("")
113 self._files = datastructures.MultiValueDict ()
114 # end def _load_post_and_files
115
116 def _get_request(self):
117 if self._request is None :
118 self._request = datastructures.MergeDict (self.POST, self.GET)
119 return self._request
120 # end def _get_request
121
122 def _get_get(self):
123 if self._get is None :
124 self._get = http.QueryDict (self.environ.get ("QUERY_STRING", ""))
125 return self._get
126 # end def _get_get
127
128 def _set_get(self, get) :
129 self._get = get
130 # end def _set_get
131
132 def _get_post(self):
133 if self._post is None:
134 self._load_post_and_files ()
135 return self._post
136 # end def _get_post
137
138 def _set_post(self, post):
139 self._post = post
140 # end def _set_post
141
142 def _get_cookies(self):
143 if self._cookies is None :
144 self._cookies = http.parse_cookie \
145 (self.environ.get ("HTTP_COOKIE", ""))
146 return self._cookies
147 # end def _get_cookies
148
149 def _set_cookies(self, cookies):
150 self._cookies = cookies
151 # end def _set_cookies
152
153 def _get_files(self):
154 if self._files is None :
155 self._load_post_and_files ()
156 return self._files
157 # end def _get_files
158
159 def _get_raw_post_data(self):
160 try:
161 return self._raw_post_data
162 except AttributeError:
163 self._raw_post_data = sys.stdin.read \
164 (int (self.environ ["CONTENT_LENGTH"]))
165 return self._raw_post_data
166 # end def _get_raw_post_data
167
168 GET = property (_get_get, _set_get)
169 POST = property (_get_post, _set_post)
170 COOKIES = property (_get_cookies, _set_cookies)
171 FILES = property (_get_files)
172 REQUEST = property (_get_request)
173 raw_post_data = property (_get_raw_post_data)
174
175# end class CGI_Request
176
177class CGI_Handler (BaseHandler) :
178 """The handler for a CGI request."""
179
180 def __call__ (self, environ, start_response) :
181 from django.conf import settings
182
183 # Set up middleware if needed. We couldn't do this earlier, because
184 # settings weren't available.
185 if self._request_middleware is None:
186 self.load_middleware ()
187
188 dispatcher.send (signal = signals.request_started)
189 try:
190 request = CGI_Request (environ)
191 response = self.get_response (request.path, request)
192 # Apply response middleware
193 for middleware_method in self._response_middleware:
194 response = middleware_method (request, response)
195 finally:
196 dispatcher.send (signal = signals.request_finished)
197
198 status_text = STATUS_CODE_TEXT.get \
199 (response.status_code, "UNKNOWN STATUS CODE")
200 status = '%s %s' % (response.status_code, status_text)
201 response_headers = response.headers.items ()
202 for c in response.cookies.values ():
203 response_headers.append (('Set-Cookie', c.output(header='')))
204 start_response (status, response_headers)
205 return response.iterator
206 # end def __call__
207
208# end class CGI_Handler
Back to Top