~canonical-django/canonical-django/project-template

« back to all changes in this revision

Viewing changes to trunk/python-packages/django/core/handlers/modpython.py

  • Committer: Matthew Nuzum
  • Date: 2008-11-13 05:46:03 UTC
  • Revision ID: matthew.nuzum@canonical.com-20081113054603-v0kvr6z6xyexvqt3
adding to version control

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
from pprint import pformat
 
3
 
 
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
 
10
 
 
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).
 
14
 
 
15
class ModPythonRequest(http.HttpRequest):
 
16
    def __init__(self, req):
 
17
        self._req = 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
 
22
        # encoding/decoding.
 
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):])
 
31
        else:
 
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.
 
37
            self.path_info = u'/'
 
38
        self._post_parse_error = False
 
39
 
 
40
    def __repr__(self):
 
41
        # Since this is called as part of error handling, we need to be very
 
42
        # robust against potentially malformed input.
 
43
        try:
 
44
            get = pformat(self.GET)
 
45
        except:
 
46
            get = '<could not parse>'
 
47
        if self._post_parse_error:
 
48
            post = '<could not parse>'
 
49
        else:
 
50
            try:
 
51
                post = pformat(self.POST)
 
52
            except:
 
53
                post = '<could not parse>'
 
54
        try:
 
55
            cookies = pformat(self.COOKIES)
 
56
        except:
 
57
            cookies = '<could not parse>'
 
58
        try:
 
59
            meta = pformat(self.META)
 
60
        except:
 
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)))
 
65
 
 
66
    def get_full_path(self):
 
67
        return '%s%s' % (self.path, self._req.args and ('?' + self._req.args) or '')
 
68
 
 
69
    def is_secure(self):
 
70
        try:
 
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')
 
75
 
 
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 = ''
 
80
            try:
 
81
                self._post, self._files = self.parse_file_upload(self.META, self._req)
 
82
            except:
 
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
 
88
                raise
 
89
        else:
 
90
            self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict()
 
91
 
 
92
    def _get_request(self):
 
93
        if not hasattr(self, '_request'):
 
94
            self._request = datastructures.MergeDict(self.POST, self.GET)
 
95
        return self._request
 
96
 
 
97
    def _get_get(self):
 
98
        if not hasattr(self, '_get'):
 
99
            self._get = http.QueryDict(self._req.args, encoding=self._encoding)
 
100
        return self._get
 
101
 
 
102
    def _set_get(self, get):
 
103
        self._get = get
 
104
 
 
105
    def _get_post(self):
 
106
        if not hasattr(self, '_post'):
 
107
            self._load_post_and_files()
 
108
        return self._post
 
109
 
 
110
    def _set_post(self, post):
 
111
        self._post = post
 
112
 
 
113
    def _get_cookies(self):
 
114
        if not hasattr(self, '_cookies'):
 
115
            self._cookies = http.parse_cookie(self._req.headers_in.get('cookie', ''))
 
116
        return self._cookies
 
117
 
 
118
    def _set_cookies(self, cookies):
 
119
        self._cookies = cookies
 
120
 
 
121
    def _get_files(self):
 
122
        if not hasattr(self, '_files'):
 
123
            self._load_post_and_files()
 
124
        return self._files
 
125
 
 
126
    def _get_meta(self):
 
127
        "Lazy loader that returns self.META dictionary"
 
128
        if not hasattr(self, '_meta'):
 
129
            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'
 
147
            }
 
148
            for key, value in self._req.headers_in.items():
 
149
                key = 'HTTP_' + key.upper().replace('-', '_')
 
150
                self._meta[key] = value
 
151
        return self._meta
 
152
 
 
153
    def _get_raw_post_data(self):
 
154
        try:
 
155
            return self._raw_post_data
 
156
        except AttributeError:
 
157
            self._raw_post_data = self._req.read()
 
158
            return self._raw_post_data
 
159
 
 
160
    def _get_method(self):
 
161
        return self.META['REQUEST_METHOD'].upper()
 
162
 
 
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)
 
171
 
 
172
class ModPythonHandler(BaseHandler):
 
173
    request_class = ModPythonRequest
 
174
 
 
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)
 
178
 
 
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
 
182
 
 
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()
 
186
 
 
187
        set_script_prefix(req.get_options().get('django.root', ''))
 
188
        signals.request_started.send(sender=self.__class__)
 
189
        try:
 
190
            try:
 
191
                request = self.request_class(req)
 
192
            except UnicodeDecodeError:
 
193
                response = http.HttpResponseBadRequest()
 
194
            else:
 
195
                response = self.get_response(request)
 
196
 
 
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)
 
201
        finally:
 
202
            signals.request_finished.send(sender=self.__class__)
 
203
 
 
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
 
212
        try:
 
213
            for chunk in response:
 
214
                req.write(chunk)
 
215
        finally:
 
216
            response.close()
 
217
 
 
218
        return 0 # mod_python.apache.OK
 
219
 
 
220
def handler(req):
 
221
    # mod_python hooks into this function.
 
222
    return ModPythonHandler()(req)