Ticket #376: modpython2.2.py

File modpython2.2.py, 6.3 KB (added by Sanel, 18 years ago)

Modified Manuzhai's patch for 0.95

Line 
1from django.core.handlers.base import BaseHandler
2from django.core import signals
3from django.dispatch import dispatcher
4from django.utils import datastructures
5from django import http
6from pprint import pformat
7import os
8
9# NOTE: do *not* import settings (or any module which eventually imports
10# settings) until after ModPythonHandler has been called; otherwise os.environ
11# won't be set up correctly (with respect to settings).
12
13class ModPythonRequest(http.HttpRequest):
14 def __init__(self, req):
15 self._req = req
16 self.path = req.uri
17
18 def __repr__(self):
19 return '<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \
20 (self.path, pformat(self.GET), pformat(self.POST), pformat(self.COOKIES),
21 pformat(self.META))
22
23 def get_full_path(self):
24 return '%s%s' % (self.path, self._req.args and ('?' + self._req.args) or '')
25
26 def is_secure(self):
27 return self._req.subprocess_env.has_key('HTTPS') and self._req.subprocess_env['HTTPS'] == 'on'
28
29 def _load_post_and_files(self):
30 "Populates self._post and self._files"
31 if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):
32 self._post, self._files = http.parse_file_upload(self._req.headers_in, self.raw_post_data)
33 else:
34 self._post, self._files = http.QueryDict(self.raw_post_data), datastructures.MultiValueDict()
35
36 def _get_request(self):
37 if not hasattr(self, '_request'):
38 self._request = datastructures.MergeDict(self.POST, self.GET)
39 return self._request
40
41 def _get_get(self):
42 if not hasattr(self, '_get'):
43 self._get = http.QueryDict(self._req.args)
44 return self._get
45
46 def _set_get(self, get):
47 self._get = get
48
49 def _get_post(self):
50 if not hasattr(self, '_post'):
51 self._load_post_and_files()
52 return self._post
53
54 def _set_post(self, post):
55 self._post = post
56
57 def _get_cookies(self):
58 if not hasattr(self, '_cookies'):
59 if self._req.headers_in.has_key('cookie'):
60 self._cookies = http.parse_cookie(self._req.headers_in['cookie'])
61 else:
62 self._cookies = http.parse_cookie('')
63 return self._cookies
64
65 def _set_cookies(self, cookies):
66 self._cookies = cookies
67
68 def _get_files(self):
69 if not hasattr(self, '_files'):
70 self._load_post_and_files()
71 return self._files
72
73 def _get_meta(self):
74 "Lazy loader that returns self.META dictionary"
75 if not hasattr(self, '_meta'):
76 self._meta = {
77 'AUTH_TYPE': self._req.connection.ap_auth_type,
78 'CONTENT_LENGTH': self._req.clength, # This may be wrong
79 'CONTENT_TYPE': self._req.content_type, # This may be wrong
80 'GATEWAY_INTERFACE': 'CGI/1.1',
81 'PATH_INFO': self._req.path_info,
82 'PATH_TRANSLATED': None, # Not supported
83 'QUERY_STRING': self._req.args,
84 'REMOTE_ADDR': self._req.connection.remote_ip,
85 'REMOTE_HOST': None, # DNS lookups not supported
86 'REMOTE_IDENT': self._req.connection.remote_logname,
87 'REMOTE_USER': self._req.connection.user,
88 'REQUEST_METHOD': self._req.method,
89 'SCRIPT_NAME': None, # Not supported
90 'SERVER_NAME': self._req.server.server_hostname,
91 'SERVER_PORT': self._req.server.port,
92 'SERVER_PROTOCOL': self._req.protocol,
93 'SERVER_SOFTWARE': 'mod_python'
94 }
95 for key in self._req.headers_in.keys():
96 nkey = 'HTTP_' + key.upper().replace('-', '_')
97 self._meta[nkey] = self._req.headers_in[key]
98 return self._meta
99
100 def _get_raw_post_data(self):
101 try:
102 return self._raw_post_data
103 except AttributeError:
104 self._raw_post_data = self._req.read()
105 return self._raw_post_data
106
107 def _get_method(self):
108 return self.META['REQUEST_METHOD'].upper()
109
110 GET = property(_get_get, _set_get)
111 POST = property(_get_post, _set_post)
112 COOKIES = property(_get_cookies, _set_cookies)
113 FILES = property(_get_files)
114 META = property(_get_meta)
115 REQUEST = property(_get_request)
116 raw_post_data = property(_get_raw_post_data)
117 method = property(_get_method)
118
119class ModPythonHandler(BaseHandler):
120 def __call__(self, req):
121 # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes that
122 os.environ.update(req.subprocess_env)
123
124 # now that the environ works we can see the correct settings, so imports
125 # that use settings now can work
126 from django.conf import settings
127
128 if settings.ENABLE_PSYCO:
129 import psyco
130 psyco.profile()
131
132 # if we need to set up middleware, now that settings works we can do it now.
133 if self._request_middleware is None:
134 self.load_middleware()
135
136 dispatcher.send(signal=signals.request_started)
137 try:
138 request = ModPythonRequest(req)
139 response = self.get_response(req.uri, request)
140
141 # Apply response middleware
142 for middleware_method in self._response_middleware:
143 response = middleware_method(request, response)
144
145 finally:
146 dispatcher.send(signal=signals.request_finished)
147
148 # Convert our custom HttpResponse object back into the mod_python req.
149 populate_apache_request(response, req)
150 return 0 # mod_python.apache.OK
151
152def populate_apache_request(http_response, mod_python_req):
153 "Populates the mod_python request object with an HttpResponse"
154 mod_python_req.content_type = http_response['Content-Type']
155 for key, value in http_response.headers.items():
156 if key != 'Content-Type':
157 mod_python_req.headers_out[key] = value
158 for c in http_response.cookies.values():
159 mod_python_req.headers_out.add('Set-Cookie', c.output(header=''))
160 mod_python_req.status = http_response.status_code
161 for chunk in http_response.iterator:
162 mod_python_req.write(chunk)
163
164def handler(req):
165 # mod_python hooks into this function.
166 return ModPythonHandler()(req)
Back to Top