Django

Code

root/django/trunk/django/core/handlers/wsgi.py

Revision 8748, 9.3 kB (checked in by jacob, 3 months ago)

Fixed #8622: accessing POST after a POST handling exception no longer throws the server into an infinite loop. Thanks to vung for tracking this one down and fixing it.

  • Property svn:eol-style set to native
Line 
1 from threading import Lock
2 from pprint import pformat
3 try:
4     from cStringIO import StringIO
5 except ImportError:
6     from StringIO import StringIO
7
8 from django import http
9 from django.core import signals
10 from django.core.handlers import base
11 from django.core.urlresolvers import set_script_prefix
12 from django.utils import datastructures
13 from django.utils.encoding import force_unicode
14
15 # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
16 STATUS_CODE_TEXT = {
17     100: 'CONTINUE',
18     101: 'SWITCHING PROTOCOLS',
19     200: 'OK',
20     201: 'CREATED',
21     202: 'ACCEPTED',
22     203: 'NON-AUTHORITATIVE INFORMATION',
23     204: 'NO CONTENT',
24     205: 'RESET CONTENT',
25     206: 'PARTIAL CONTENT',
26     300: 'MULTIPLE CHOICES',
27     301: 'MOVED PERMANENTLY',
28     302: 'FOUND',
29     303: 'SEE OTHER',
30     304: 'NOT MODIFIED',
31     305: 'USE PROXY',
32     306: 'RESERVED',
33     307: 'TEMPORARY REDIRECT',
34     400: 'BAD REQUEST',
35     401: 'UNAUTHORIZED',
36     402: 'PAYMENT REQUIRED',
37     403: 'FORBIDDEN',
38     404: 'NOT FOUND',
39     405: 'METHOD NOT ALLOWED',
40     406: 'NOT ACCEPTABLE',
41     407: 'PROXY AUTHENTICATION REQUIRED',
42     408: 'REQUEST TIMEOUT',
43     409: 'CONFLICT',
44     410: 'GONE',
45     411: 'LENGTH REQUIRED',
46     412: 'PRECONDITION FAILED',
47     413: 'REQUEST ENTITY TOO LARGE',
48     414: 'REQUEST-URI TOO LONG',
49     415: 'UNSUPPORTED MEDIA TYPE',
50     416: 'REQUESTED RANGE NOT SATISFIABLE',
51     417: 'EXPECTATION FAILED',
52     500: 'INTERNAL SERVER ERROR',
53     501: 'NOT IMPLEMENTED',
54     502: 'BAD GATEWAY',
55     503: 'SERVICE UNAVAILABLE',
56     504: 'GATEWAY TIMEOUT',
57     505: 'HTTP VERSION NOT SUPPORTED',
58 }
59
60 def safe_copyfileobj(fsrc, fdst, length=16*1024, size=0):
61     """
62     A version of shutil.copyfileobj that will not read more than 'size' bytes.
63     This makes it safe from clients sending more than CONTENT_LENGTH bytes of
64     data in the body.
65     """
66     if not size:
67         return
68     while size > 0:
69         buf = fsrc.read(min(length, size))
70         if not buf:
71             break
72         fdst.write(buf)
73         size -= len(buf)
74
75 class WSGIRequest(http.HttpRequest):
76     def __init__(self, environ):
77         script_name = base.get_script_name(environ)
78         path_info = force_unicode(environ.get('PATH_INFO', u'/'))
79         if not path_info or path_info == script_name:
80             # Sometimes PATH_INFO exists, but is empty (e.g. accessing
81             # the SCRIPT_NAME URL without a trailing slash). We really need to
82             # operate as if they'd requested '/'. Not amazingly nice to force
83             # the path like this, but should be harmless.
84             #
85             # (The comparison of path_info to script_name is to work around an
86             # apparent bug in flup 1.0.1. Se Django ticket #8490).
87             path_info = u'/'
88         self.environ = environ
89         self.path_info = path_info
90         self.path = '%s%s' % (script_name, path_info)
91         self.META = environ
92         self.META['PATH_INFO'] = path_info
93         self.META['SCRIPT_NAME'] = script_name
94         self.method = environ['REQUEST_METHOD'].upper()
95         self._post_parse_error = False
96
97     def __repr__(self):
98         # Since this is called as part of error handling, we need to be very
99         # robust against potentially malformed input.
100         try:
101             get = pformat(self.GET)
102         except:
103             get = '<could not parse>'
104         if self._post_parse_error:
105             post = '<could not parse>'
106         else:
107             try:
108                 post = pformat(self.POST)
109             except:
110                 post = '<could not parse>'
111         try:
112             cookies = pformat(self.COOKIES)
113         except:
114             cookies = '<could not parse>'
115         try:
116             meta = pformat(self.META)
117         except:
118             meta = '<could not parse>'
119         return '<WSGIRequest\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \
120             (get, post, cookies, meta)
121
122     def get_full_path(self):
123         return '%s%s' % (self.path, self.environ.get('QUERY_STRING', '') and ('?' + self.environ.get('QUERY_STRING', '')) or '')
124
125     def is_secure(self):
126         return 'wsgi.url_scheme' in self.environ \
127             and self.environ['wsgi.url_scheme'] == 'https'
128
129     def _load_post_and_files(self):
130         # Populates self._post and self._files
131         if self.method == 'POST':
132             if self.environ.get('CONTENT_TYPE', '').startswith('multipart'):
133                 self._raw_post_data = ''
134                 try:
135                     self._post, self._files = self.parse_file_upload(self.META, self.environ['wsgi.input'])
136                 except:
137                     # An error occured while parsing POST data.  Since when
138                     # formatting the error the request handler might access
139                     # self.POST, set self._post and self._file to prevent
140                     # attempts to parse POST data again.
141                     self._post = http.QueryDict('')
142                     self._files = datastructures.MultiValueDict()
143                     # Mark that an error occured.  This allows self.__repr__ to
144                     # be explicit about it instead of simply representing an
145                     # empty POST
146                     self._post_parse_error = True
147                     raise
148             else:
149                 self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict()
150         else:
151             self._post, self._files = http.QueryDict('', encoding=self._encoding), datastructures.MultiValueDict()
152
153     def _get_request(self):
154         if not hasattr(self, '_request'):
155             self._request = datastructures.MergeDict(self.POST, self.GET)
156         return self._request
157
158     def _get_get(self):
159         if not hasattr(self, '_get'):
160             # The WSGI spec says 'QUERY_STRING' may be absent.
161             self._get = http.QueryDict(self.environ.get('QUERY_STRING', ''), encoding=self._encoding)
162         return self._get
163
164     def _set_get(self, get):
165         self._get = get
166
167     def _get_post(self):
168         if not hasattr(self, '_post'):
169             self._load_post_and_files()
170         return self._post
171
172     def _set_post(self, post):
173         self._post = post
174
175     def _get_cookies(self):
176         if not hasattr(self, '_cookies'):
177             self._cookies = http.parse_cookie(self.environ.get('HTTP_COOKIE', ''))
178         return self._cookies
179
180     def _set_cookies(self, cookies):
181         self._cookies = cookies
182
183     def _get_files(self):
184         if not hasattr(self, '_files'):
185             self._load_post_and_files()
186         return self._files
187
188     def _get_raw_post_data(self):
189         try:
190             return self._raw_post_data
191         except AttributeError:
192             buf = StringIO()
193             try:
194                 # CONTENT_LENGTH might be absent if POST doesn't have content at all (lighttpd)
195                 content_length = int(self.environ.get('CONTENT_LENGTH', 0))
196             except (ValueError, TypeError):
197                 # If CONTENT_LENGTH was empty string or not an integer, don't
198                 # error out. We've also seen None passed in here (against all
199                 # specs, but see ticket #8259), so we handle TypeError as well.
200                 content_length = 0
201             if content_length > 0:
202                 safe_copyfileobj(self.environ['wsgi.input'], buf,
203                         size=content_length)
204             self._raw_post_data = buf.getvalue()
205             buf.close()
206             return self._raw_post_data
207
208     GET = property(_get_get, _set_get)
209     POST = property(_get_post, _set_post)
210     COOKIES = property(_get_cookies, _set_cookies)
211     FILES = property(_get_files)
212     REQUEST = property(_get_request)
213     raw_post_data = property(_get_raw_post_data)
214
215 class WSGIHandler(base.BaseHandler):
216     initLock = Lock()
217     request_class = WSGIRequest
218
219     def __call__(self, environ, start_response):
220         from django.conf import settings
221
222         # Set up middleware if needed. We couldn't do this earlier, because
223         # settings weren't available.
224         if self._request_middleware is None:
225             self.initLock.acquire()
226             # Check that middleware is still uninitialised.
227             if self._request_middleware is None:
228                 self.load_middleware()
229             self.initLock.release()
230
231         set_script_prefix(base.get_script_name(environ))
232         signals.request_started.send(sender=self.__class__)
233         try:
234             try:
235                 request = self.request_class(environ)
236             except UnicodeDecodeError:
237                 response = http.HttpResponseBadRequest()
238             else:
239                 response = self.get_response(request)
240
241                 # Apply response middleware
242                 for middleware_method in self._response_middleware:
243                     response = middleware_method(request, response)
244                 response = self.apply_response_fixes(request, response)
245         finally:
246             signals.request_finished.send(sender=self.__class__)
247
248         try:
249             status_text = STATUS_CODE_TEXT[response.status_code]
250         except KeyError:
251             status_text = 'UNKNOWN STATUS CODE'
252         status = '%s %s' % (response.status_code, status_text)
253         response_headers = [(str(k), str(v)) for k, v in response.items()]
254         for c in response.cookies.values():
255             response_headers.append(('Set-Cookie', str(c.output(header=''))))
256         start_response(status, response_headers)
257         return response
Note: See TracBrowser for help on using the browser.