2
from pprint import pformat
4
from django import http
5
from django.core import signals
6
from django.core.handlers.base import BaseHandler
7
from django.core.urlresolvers import set_script_prefix
8
from django.utils import datastructures
9
from django.utils.encoding import force_unicode, smart_str
11
# NOTE: do *not* import settings (or any module which eventually imports
12
# settings) until after ModPythonHandler has been called; otherwise os.environ
13
# won't be set up correctly (with respect to settings).
15
class ModPythonRequest(http.HttpRequest):
16
def __init__(self, req):
18
# FIXME: This isn't ideal. The request URI may be encoded (it's
19
# non-normalized) slightly differently to the "real" SCRIPT_NAME
20
# and PATH_INFO values. This causes problems when we compute path_info,
21
# below. For now, don't use script names that will be subject to
23
self.path = force_unicode(req.uri)
24
root = req.get_options().get('django.root', '')
25
self.django_root = root
26
# req.path_info isn't necessarily computed correctly in all
27
# circumstances (it's out of mod_python's control a bit), so we use
28
# req.uri and some string manipulations to get the right value.
29
if root and req.uri.startswith(root):
30
self.path_info = force_unicode(req.uri[len(root):])
32
self.path_info = self.path
33
if not self.path_info:
34
# Django prefers empty paths to be '/', rather than '', to give us
35
# a common start character for URL patterns. So this is a little
36
# naughty, but also pretty harmless.
38
self._post_parse_error = False
41
# Since this is called as part of error handling, we need to be very
42
# robust against potentially malformed input.
44
get = pformat(self.GET)
46
get = '<could not parse>'
47
if self._post_parse_error:
48
post = '<could not parse>'
51
post = pformat(self.POST)
53
post = '<could not parse>'
55
cookies = pformat(self.COOKIES)
57
cookies = '<could not parse>'
59
meta = pformat(self.META)
61
meta = '<could not parse>'
62
return smart_str(u'<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
63
(self.path, unicode(get), unicode(post),
64
unicode(cookies), unicode(meta)))
66
def get_full_path(self):
67
return '%s%s' % (self.path, self._req.args and ('?' + self._req.args) or '')
71
return self._req.is_https()
72
except AttributeError:
73
# mod_python < 3.2.10 doesn't have req.is_https().
74
return self._req.subprocess_env.get('HTTPS', '').lower() in ('on', '1')
76
def _load_post_and_files(self):
77
"Populates self._post and self._files"
78
if 'content-type' in self._req.headers_in and self._req.headers_in['content-type'].startswith('multipart'):
79
self._raw_post_data = ''
81
self._post, self._files = self.parse_file_upload(self.META, self._req)
83
# See django.core.handlers.wsgi.WSGIHandler for an explanation
84
# of what's going on here.
85
self._post = http.QueryDict('')
86
self._files = datastructures.MultiValueDict()
87
self._post_parse_error = True
90
self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict()
92
def _get_request(self):
93
if not hasattr(self, '_request'):
94
self._request = datastructures.MergeDict(self.POST, self.GET)
98
if not hasattr(self, '_get'):
99
self._get = http.QueryDict(self._req.args, encoding=self._encoding)
102
def _set_get(self, get):
106
if not hasattr(self, '_post'):
107
self._load_post_and_files()
110
def _set_post(self, post):
113
def _get_cookies(self):
114
if not hasattr(self, '_cookies'):
115
self._cookies = http.parse_cookie(self._req.headers_in.get('cookie', ''))
118
def _set_cookies(self, cookies):
119
self._cookies = cookies
121
def _get_files(self):
122
if not hasattr(self, '_files'):
123
self._load_post_and_files()
127
"Lazy loader that returns self.META dictionary"
128
if not hasattr(self, '_meta'):
130
'AUTH_TYPE': self._req.ap_auth_type,
131
'CONTENT_LENGTH': self._req.clength, # This may be wrong
132
'CONTENT_TYPE': self._req.content_type, # This may be wrong
133
'GATEWAY_INTERFACE': 'CGI/1.1',
134
'PATH_INFO': self.path_info,
135
'PATH_TRANSLATED': None, # Not supported
136
'QUERY_STRING': self._req.args,
137
'REMOTE_ADDR': self._req.connection.remote_ip,
138
'REMOTE_HOST': None, # DNS lookups not supported
139
'REMOTE_IDENT': self._req.connection.remote_logname,
140
'REMOTE_USER': self._req.user,
141
'REQUEST_METHOD': self._req.method,
142
'SCRIPT_NAME': self.django_root,
143
'SERVER_NAME': self._req.server.server_hostname,
144
'SERVER_PORT': self._req.server.port,
145
'SERVER_PROTOCOL': self._req.protocol,
146
'SERVER_SOFTWARE': 'mod_python'
148
for key, value in self._req.headers_in.items():
149
key = 'HTTP_' + key.upper().replace('-', '_')
150
self._meta[key] = value
153
def _get_raw_post_data(self):
155
return self._raw_post_data
156
except AttributeError:
157
self._raw_post_data = self._req.read()
158
return self._raw_post_data
160
def _get_method(self):
161
return self.META['REQUEST_METHOD'].upper()
163
GET = property(_get_get, _set_get)
164
POST = property(_get_post, _set_post)
165
COOKIES = property(_get_cookies, _set_cookies)
166
FILES = property(_get_files)
167
META = property(_get_meta)
168
REQUEST = property(_get_request)
169
raw_post_data = property(_get_raw_post_data)
170
method = property(_get_method)
172
class ModPythonHandler(BaseHandler):
173
request_class = ModPythonRequest
175
def __call__(self, req):
176
# mod_python fakes the environ, and thus doesn't process SetEnv. This fixes that
177
os.environ.update(req.subprocess_env)
179
# now that the environ works we can see the correct settings, so imports
180
# that use settings now can work
181
from django.conf import settings
183
# if we need to set up middleware, now that settings works we can do it now.
184
if self._request_middleware is None:
185
self.load_middleware()
187
set_script_prefix(req.get_options().get('django.root', ''))
188
signals.request_started.send(sender=self.__class__)
191
request = self.request_class(req)
192
except UnicodeDecodeError:
193
response = http.HttpResponseBadRequest()
195
response = self.get_response(request)
197
# Apply response middleware
198
for middleware_method in self._response_middleware:
199
response = middleware_method(request, response)
200
response = self.apply_response_fixes(request, response)
202
signals.request_finished.send(sender=self.__class__)
204
# Convert our custom HttpResponse object back into the mod_python req.
205
req.content_type = response['Content-Type']
206
for key, value in response.items():
207
if key != 'content-type':
208
req.headers_out[str(key)] = str(value)
209
for c in response.cookies.values():
210
req.headers_out.add('Set-Cookie', c.output(header=''))
211
req.status = response.status_code
213
for chunk in response:
218
return 0 # mod_python.apache.OK
221
# mod_python hooks into this function.
222
return ModPythonHandler()(req)