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