Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Added WSGI support. Created core.handlers package. Moved ALL mod_pyth…

…on-specific code to django.core.handlers.modpython. Note that django.core.handler is still a valid mod_python handler but IS DEPRECATED. Use django.core.handlers.modpython, instead.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@169 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit ca3d89b70f30598d8e3a8438fcf4a0050963a21e 1 parent 4e094e2
Adrian Holovaty authored July 18, 2005
4  django/core/extensions.py
... ...
@@ -1,9 +1,7 @@
1  
-"Specialized Context and ModPythonRequest classes for Django. Use these!"
  1
+# Specialized template classes for Django, decoupled from the basic template system.
2 2
 
3 3
 from django.core.template import Context
4  
-from django.utils.httpwrappers import ModPythonRequest
5 4
 from django.conf.settings import DEBUG, INTERNAL_IPS
6  
-from pprint import pformat
7 5
 
8 6
 class DjangoContext(Context):
9 7
     """
155  django/core/handler.py
... ...
@@ -1,150 +1,11 @@
1  
-import os
2  
-from django.utils import httpwrappers
3  
-
4  
-# NOTE: do *not* import settings (or any module which eventually imports
5  
-# settings) until after ModPythonHandler has been called; otherwise os.environ
6  
-# won't be set up correctly (with respect to settings).
7  
-
8  
-class ModPythonHandler:
9  
-
10  
-    def __init__(self):
11  
-        self._request_middleware = self._view_middleware = self._response_middleware = None
12  
-
13  
-    def __call__(self, req):
14  
-        # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes that
15  
-        os.environ.update(req.subprocess_env)
16  
-
17  
-        # now that the environ works we can see the correct settings, so imports
18  
-        # that use settings now can work
19  
-        from django.conf import settings
20  
-        from django.core import db
21  
-        from django.utils.httpwrappers import ModPythonRequest
22  
-
23  
-        # if we need to set up middleware, now that settings works we can do it now.
24  
-        if self._request_middleware is None:
25  
-            self.load_middleware()
26  
-
27  
-        try:
28  
-            request = ModPythonRequest(req)
29  
-            response = self.get_response(req.uri, request)
30  
-        finally:
31  
-            db.db.close()
32  
-
33  
-        # Apply response middleware
34  
-        for middleware_method in self._response_middleware:
35  
-            response = middleware_method(request, response)
36  
-
37  
-        # Convert our custom HttpResponse object back into the mod_python req.
38  
-        httpwrappers.populate_apache_request(response, req)
39  
-        return 0 # mod_python.apache.OK
40  
-
41  
-    def load_middleware(self):
42  
-        """
43  
-        Populate middleware lists from settings.MIDDLEWARE_CLASSES.
44  
-
45  
-        Must be called after the environment is fixed (see __call__).
46  
-        """
47  
-        from django.conf import settings
48  
-        from django.core import exceptions
49  
-        self._request_middleware = []
50  
-        self._view_middleware = []
51  
-        self._response_middleware = []
52  
-        for middleware_path in settings.MIDDLEWARE_CLASSES:
53  
-            dot = middleware_path.rindex('.')
54  
-            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
55  
-            try:
56  
-                mod = __import__(mw_module, '', '', [''])
57  
-            except ImportError, e:
58  
-                raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
59  
-            try:
60  
-                mw_class = getattr(mod, mw_classname)
61  
-            except AttributeError:
62  
-                raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
63  
-
64  
-            try:
65  
-                mw_instance = mw_class()
66  
-            except exceptions.MiddlewareNotUsed:
67  
-                continue
68  
-
69  
-            if hasattr(mw_instance, 'process_request'):
70  
-                self._request_middleware.append(mw_instance.process_request)
71  
-            if hasattr(mw_instance, 'process_view'):
72  
-                self._view_middleware.append(mw_instance.process_view)
73  
-            if hasattr(mw_instance, 'process_response'):
74  
-                self._response_middleware.insert(0, mw_instance.process_response)
75  
-
76  
-    def get_response(self, path, request):
77  
-        "Returns an HttpResponse object for the given HttpRequest"
78  
-        from django.core import db, exceptions, urlresolvers
79  
-        from django.core.mail import mail_admins
80  
-        from django.conf.settings import DEBUG, INTERNAL_IPS, ROOT_URLCONF
81  
-
82  
-        # Apply request middleware
83  
-        for middleware_method in self._request_middleware:
84  
-            response = middleware_method(request)
85  
-            if response:
86  
-                return response
87  
-
88  
-        conf_module = __import__(ROOT_URLCONF, '', '', [''])
89  
-        resolver = urlresolvers.RegexURLResolver(conf_module.urlpatterns)
90  
-        try:
91  
-            callback, param_dict = resolver.resolve(path)
92  
-            # Apply view middleware
93  
-            for middleware_method in self._view_middleware:
94  
-                response = middleware_method(request, callback, param_dict)
95  
-                if response:
96  
-                    return response
97  
-            return callback(request, **param_dict)
98  
-        except exceptions.Http404:
99  
-            if DEBUG:
100  
-                return self.get_technical_error_response(is404=True)
101  
-            else:
102  
-                resolver = urlresolvers.Error404Resolver(conf_module.handler404)
103  
-                callback, param_dict = resolver.resolve()
104  
-                return callback(request, **param_dict)
105  
-        except db.DatabaseError:
106  
-            db.db.rollback()
107  
-            if DEBUG:
108  
-                return self.get_technical_error_response()
109  
-            else:
110  
-                subject = 'Database error (%s IP)' % (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
111  
-                message = "%s\n\n%s" % (self._get_traceback(), request)
112  
-                mail_admins(subject, message, fail_silently=True)
113  
-                return self.get_friendly_error_response(request, conf_module)
114  
-        except exceptions.PermissionDenied:
115  
-            return httpwrappers.HttpResponseForbidden('<h1>Permission denied</h1>')
116  
-        except: # Handle everything else, including SuspiciousOperation, etc.
117  
-            if DEBUG:
118  
-                return self.get_technical_error_response()
119  
-            else:
120  
-                subject = 'Coding error (%s IP)' % (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
121  
-                message = "%s\n\n%s" % (self._get_traceback(), request)
122  
-                mail_admins(subject, message, fail_silently=True)
123  
-                return self.get_friendly_error_response(request, conf_module)
124  
-
125  
-    def get_friendly_error_response(self, request, conf_module):
126  
-        """
127  
-        Returns an HttpResponse that displays a PUBLIC error message for a
128  
-        fundamental database or coding error.
129  
-        """
130  
-        from django.core import urlresolvers
131  
-        resolver = urlresolvers.Error404Resolver(conf_module.handler500)
132  
-        callback, param_dict = resolver.resolve()
133  
-        return callback(request, **param_dict)
134  
-
135  
-    def get_technical_error_response(self, is404=False):
136  
-        """
137  
-        Returns an HttpResponse that displays a TECHNICAL error message for a
138  
-        fundamental database or coding error.
139  
-        """
140  
-        error_string = "<pre>There's been an error:\n\n%s</pre>" % self._get_traceback()
141  
-        responseClass = is404 and httpwrappers.HttpResponseNotFound or httpwrappers.HttpResponseServerError
142  
-        return responseClass(error_string)
143  
-
144  
-    def _get_traceback(self):
145  
-        "Helper function to return the traceback as a string"
146  
-        import sys, traceback
147  
-        return '\n'.join(traceback.format_exception(*sys.exc_info()))
  1
+# This module is DEPRECATED!
  2
+#
  3
+# You should no longer be pointing your mod_python configuration
  4
+# at "django.core.handler".
  5
+#
  6
+# Use "django.core.handlers.modpython" instead.
  7
+
  8
+from django.core.handlers.modpython import ModPythonHandler
148 9
 
149 10
 def handler(req):
150 11
     return ModPythonHandler()(req)
0  django/core/handlers/__init__.py
No changes.
279  django/core/handlers/modpython.py
... ...
@@ -0,0 +1,279 @@
  1
+from django.utils import datastructures, httpwrappers
  2
+from pprint import pformat
  3
+import os
  4
+
  5
+# NOTE: do *not* import settings (or any module which eventually imports
  6
+# settings) until after ModPythonHandler has been called; otherwise os.environ
  7
+# won't be set up correctly (with respect to settings).
  8
+
  9
+class ModPythonRequest(httpwrappers.HttpRequest):
  10
+    def __init__(self, req):
  11
+        self._req = req
  12
+        self.path = req.uri
  13
+
  14
+    def __repr__(self):
  15
+        return '<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s,\nuser:%s>' % \
  16
+            (self.path, pformat(self.GET), pformat(self.POST), pformat(self.COOKIES),
  17
+            pformat(self.META), pformat(self.user))
  18
+
  19
+    def get_full_path(self):
  20
+        return '%s%s' % (self.path, self._req.args and ('?' + self._req.args) or '')
  21
+
  22
+    def _load_post_and_files(self):
  23
+        "Populates self._post and self._files"
  24
+        if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):
  25
+            self._post, self._files = httpwrappers.parse_file_upload(self._req.headers_in, self._req.read())
  26
+        else:
  27
+            self._post, self._files = httpwrappers.QueryDict(self._req.read()), datastructures.MultiValueDict()
  28
+
  29
+    def _get_request(self):
  30
+        if not hasattr(self, '_request'):
  31
+           self._request = datastructures.MergeDict(self.POST, self.GET)
  32
+        return self._request
  33
+
  34
+    def _get_get(self):
  35
+        if not hasattr(self, '_get'):
  36
+            self._get = httpwrappers.QueryDict(self._req.args)
  37
+        return self._get
  38
+
  39
+    def _set_get(self, get):
  40
+        self._get = get
  41
+
  42
+    def _get_post(self):
  43
+        if not hasattr(self, '_post'):
  44
+            self._load_post_and_files()
  45
+        return self._post
  46
+
  47
+    def _set_post(self, post):
  48
+        self._post = post
  49
+
  50
+    def _get_cookies(self):
  51
+        if not hasattr(self, '_cookies'):
  52
+            self._cookies = httpwrappers.parse_cookie(self._req.headers_in.get('cookie', ''))
  53
+        return self._cookies
  54
+
  55
+    def _set_cookies(self, cookies):
  56
+        self._cookies = cookies
  57
+
  58
+    def _get_files(self):
  59
+        if not hasattr(self, '_files'):
  60
+            self._load_post_and_files()
  61
+        return self._files
  62
+
  63
+    def _get_meta(self):
  64
+        "Lazy loader that returns self.META dictionary"
  65
+        if not hasattr(self, '_meta'):
  66
+            self._meta = {
  67
+                'AUTH_TYPE':         self._req.ap_auth_type,
  68
+                'CONTENT_LENGTH':    self._req.clength, # This may be wrong
  69
+                'CONTENT_TYPE':      self._req.content_type, # This may be wrong
  70
+                'GATEWAY_INTERFACE': 'CGI/1.1',
  71
+                'PATH_INFO':         self._req.path_info,
  72
+                'PATH_TRANSLATED':   None, # Not supported
  73
+                'QUERY_STRING':      self._req.args,
  74
+                'REMOTE_ADDR':       self._req.connection.remote_ip,
  75
+                'REMOTE_HOST':       None, # DNS lookups not supported
  76
+                'REMOTE_IDENT':      self._req.connection.remote_logname,
  77
+                'REMOTE_USER':       self._req.user,
  78
+                'REQUEST_METHOD':    self._req.method,
  79
+                'SCRIPT_NAME':       None, # Not supported
  80
+                'SERVER_NAME':       self._req.server.server_hostname,
  81
+                'SERVER_PORT':       self._req.server.port,
  82
+                'SERVER_PROTOCOL':   self._req.protocol,
  83
+                'SERVER_SOFTWARE':   'mod_python'
  84
+            }
  85
+            for key, value in self._req.headers_in.items():
  86
+                key = 'HTTP_' + key.upper().replace('-', '_')
  87
+                self._meta[key] = value
  88
+        return self._meta
  89
+
  90
+    def _load_session_and_user(self):
  91
+        from django.models.auth import sessions
  92
+        from django.conf.settings import AUTH_SESSION_COOKIE
  93
+        session_cookie = self.COOKIES.get(AUTH_SESSION_COOKIE, '')
  94
+        try:
  95
+            self._session = sessions.get_session_from_cookie(session_cookie)
  96
+            self._user = self._session.get_user()
  97
+        except sessions.SessionDoesNotExist:
  98
+            from django.parts.auth import anonymoususers
  99
+            self._session = None
  100
+            self._user = anonymoususers.AnonymousUser()
  101
+
  102
+    def _get_session(self):
  103
+        if not hasattr(self, '_session'):
  104
+            self._load_session_and_user()
  105
+        return self._session
  106
+
  107
+    def _set_session(self, session):
  108
+        self._session = session
  109
+
  110
+    def _get_user(self):
  111
+        if not hasattr(self, '_user'):
  112
+            self._load_session_and_user()
  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
+    session = property(_get_session, _set_session)
  125
+    user = property(_get_user, _set_user)
  126
+
  127
+class ModPythonHandler:
  128
+    def __init__(self):
  129
+        self._request_middleware = self._view_middleware = self._response_middleware = None
  130
+
  131
+    def __call__(self, req):
  132
+        # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes that
  133
+        os.environ.update(req.subprocess_env)
  134
+
  135
+        # now that the environ works we can see the correct settings, so imports
  136
+        # that use settings now can work
  137
+        from django.conf import settings
  138
+        from django.core import db
  139
+
  140
+        # if we need to set up middleware, now that settings works we can do it now.
  141
+        if self._request_middleware is None:
  142
+            self.load_middleware()
  143
+
  144
+        try:
  145
+            request = ModPythonRequest(req)
  146
+            response = self.get_response(req.uri, request)
  147
+        finally:
  148
+            db.db.close()
  149
+
  150
+        # Apply response middleware
  151
+        for middleware_method in self._response_middleware:
  152
+            response = middleware_method(request, response)
  153
+
  154
+        # Convert our custom HttpResponse object back into the mod_python req.
  155
+        populate_apache_request(response, req)
  156
+        return 0 # mod_python.apache.OK
  157
+
  158
+    def load_middleware(self):
  159
+        """
  160
+        Populate middleware lists from settings.MIDDLEWARE_CLASSES.
  161
+
  162
+        Must be called after the environment is fixed (see __call__).
  163
+        """
  164
+        from django.conf import settings
  165
+        from django.core import exceptions
  166
+        self._request_middleware = []
  167
+        self._view_middleware = []
  168
+        self._response_middleware = []
  169
+        for middleware_path in settings.MIDDLEWARE_CLASSES:
  170
+            dot = middleware_path.rindex('.')
  171
+            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
  172
+            try:
  173
+                mod = __import__(mw_module, '', '', [''])
  174
+            except ImportError, e:
  175
+                raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
  176
+            try:
  177
+                mw_class = getattr(mod, mw_classname)
  178
+            except AttributeError:
  179
+                raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
  180
+
  181
+            try:
  182
+                mw_instance = mw_class()
  183
+            except exceptions.MiddlewareNotUsed:
  184
+                continue
  185
+
  186
+            if hasattr(mw_instance, 'process_request'):
  187
+                self._request_middleware.append(mw_instance.process_request)
  188
+            if hasattr(mw_instance, 'process_view'):
  189
+                self._view_middleware.append(mw_instance.process_view)
  190
+            if hasattr(mw_instance, 'process_response'):
  191
+                self._response_middleware.insert(0, mw_instance.process_response)
  192
+
  193
+    def get_response(self, path, request):
  194
+        "Returns an HttpResponse object for the given HttpRequest"
  195
+        from django.core import db, exceptions, urlresolvers
  196
+        from django.core.mail import mail_admins
  197
+        from django.conf.settings import DEBUG, INTERNAL_IPS, ROOT_URLCONF
  198
+
  199
+        # Apply request middleware
  200
+        for middleware_method in self._request_middleware:
  201
+            response = middleware_method(request)
  202
+            if response:
  203
+                return response
  204
+
  205
+        conf_module = __import__(ROOT_URLCONF, '', '', [''])
  206
+        resolver = urlresolvers.RegexURLResolver(conf_module.urlpatterns)
  207
+        try:
  208
+            callback, param_dict = resolver.resolve(path)
  209
+            # Apply view middleware
  210
+            for middleware_method in self._view_middleware:
  211
+                response = middleware_method(request, callback, param_dict)
  212
+                if response:
  213
+                    return response
  214
+            return callback(request, **param_dict)
  215
+        except exceptions.Http404:
  216
+            if DEBUG:
  217
+                return self.get_technical_error_response(is404=True)
  218
+            else:
  219
+                resolver = urlresolvers.Error404Resolver(conf_module.handler404)
  220
+                callback, param_dict = resolver.resolve()
  221
+                return callback(request, **param_dict)
  222
+        except db.DatabaseError:
  223
+            db.db.rollback()
  224
+            if DEBUG:
  225
+                return self.get_technical_error_response()
  226
+            else:
  227
+                subject = 'Database error (%s IP)' % (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
  228
+                message = "%s\n\n%s" % (self._get_traceback(), request)
  229
+                mail_admins(subject, message, fail_silently=True)
  230
+                return self.get_friendly_error_response(request, conf_module)
  231
+        except exceptions.PermissionDenied:
  232
+            return httpwrappers.HttpResponseForbidden('<h1>Permission denied</h1>')
  233
+        except: # Handle everything else, including SuspiciousOperation, etc.
  234
+            if DEBUG:
  235
+                return self.get_technical_error_response()
  236
+            else:
  237
+                subject = 'Coding error (%s IP)' % (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
  238
+                message = "%s\n\n%s" % (self._get_traceback(), request)
  239
+                mail_admins(subject, message, fail_silently=True)
  240
+                return self.get_friendly_error_response(request, conf_module)
  241
+
  242
+    def get_friendly_error_response(self, request, conf_module):
  243
+        """
  244
+        Returns an HttpResponse that displays a PUBLIC error message for a
  245
+        fundamental database or coding error.
  246
+        """
  247
+        from django.core import urlresolvers
  248
+        resolver = urlresolvers.Error404Resolver(conf_module.handler500)
  249
+        callback, param_dict = resolver.resolve()
  250
+        return callback(request, **param_dict)
  251
+
  252
+    def get_technical_error_response(self, is404=False):
  253
+        """
  254
+        Returns an HttpResponse that displays a TECHNICAL error message for a
  255
+        fundamental database or coding error.
  256
+        """
  257
+        error_string = "<pre>There's been an error:\n\n%s</pre>" % self._get_traceback()
  258
+        responseClass = is404 and httpwrappers.HttpResponseNotFound or httpwrappers.HttpResponseServerError
  259
+        return responseClass(error_string)
  260
+
  261
+    def _get_traceback(self):
  262
+        "Helper function to return the traceback as a string"
  263
+        import sys, traceback
  264
+        return '\n'.join(traceback.format_exception(*sys.exc_info()))
  265
+
  266
+def populate_apache_request(http_response, mod_python_req):
  267
+    "Populates the mod_python request object with an HttpResponse"
  268
+    mod_python_req.content_type = http_response['Content-Type'] or httpwrappers.DEFAULT_MIME_TYPE
  269
+    del http_response['Content-Type']
  270
+    if http_response.cookies:
  271
+        mod_python_req.headers_out['Set-Cookie'] = http_response.cookies.output(header='')
  272
+    for key, value in http_response.headers.items():
  273
+        mod_python_req.headers_out[key] = value
  274
+    mod_python_req.status = http_response.status_code
  275
+    mod_python_req.write(http_response.get_content_as_string('utf-8'))
  276
+
  277
+def handler(req):
  278
+    # mod_python hooks into this function.
  279
+    return ModPythonHandler()(req)
242  django/core/handlers/wsgi.py
... ...
@@ -0,0 +1,242 @@
  1
+from django.utils import datastructures, httpwrappers
  2
+from pprint import pformat
  3
+
  4
+class WSGIRequest(httpwrappers.HttpRequest):
  5
+    def __init__(self, environ):
  6
+        self.environ = environ
  7
+        self.path = environ['PATH_INFO']
  8
+        self.META = environ
  9
+
  10
+    def __repr__(self):
  11
+        from pprint import pformat
  12
+        return '<DjangoRequest\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \
  13
+            (pformat(self.GET), pformat(self.POST), pformat(self.COOKIES),
  14
+            pformat(self.META))
  15
+
  16
+    def get_full_path(self):
  17
+        return '%s%s' % (self.path, self.environ['QUERY_STRING'] and ('?' + self.environ['QUERY_STRING']) or '')
  18
+
  19
+    def _load_post_and_files(self):
  20
+        # Populates self._post and self._files
  21
+        if self.environ['REQUEST_METHOD'] == 'POST':
  22
+            post_data = self.environ['wsgi.input'].read(int(self.environ["CONTENT_LENGTH"]))
  23
+            if self.environ.get('CONTENT_TYPE', '').startswith('multipart'):
  24
+                header_dict = dict([(k, v) for k, v in self.environ.items() if k.startswith('HTTP_')])
  25
+                self._post, self._files = httpwrappers.parse_file_upload(header_dict, post_data)
  26
+            else:
  27
+                self._post, self._files = httpwrappers.QueryDict(post_data), datastructures.MultiValueDict()
  28
+        else:
  29
+            self._post, self._files = httpwrappers.QueryDict(''), datastructures.MultiValueDict()
  30
+
  31
+    def _get_request(self):
  32
+        if not hasattr(self, '_request'):
  33
+           self._request = datastructures.MergeDict(self.POST, self.GET)
  34
+        return self._request
  35
+
  36
+    def _get_get(self):
  37
+        if not hasattr(self, '_get'):
  38
+            self._get = httpwrappers.QueryDict(self.environ['QUERY_STRING'])
  39
+        return self._get
  40
+
  41
+    def _set_get(self, get):
  42
+        self._get = get
  43
+
  44
+    def _get_post(self):
  45
+        if not hasattr(self, '_post'):
  46
+            self._load_post_and_files()
  47
+        return self._post
  48
+
  49
+    def _set_post(self, post):
  50
+        self._post = post
  51
+
  52
+    def _get_cookies(self):
  53
+        if not hasattr(self, '_cookies'):
  54
+            self._cookies = httpwrappers.parse_cookie(self.environ.get('HTTP_COOKIE', ''))
  55
+        return self._cookies
  56
+
  57
+    def _set_cookies(self, cookies):
  58
+        self._cookies = cookies
  59
+
  60
+    def _get_files(self):
  61
+        if not hasattr(self, '_files'):
  62
+            self._load_post_and_files()
  63
+        return self._files
  64
+
  65
+    def _load_session_and_user(self):
  66
+        from django.models.auth import sessions
  67
+        from django.conf.settings import AUTH_SESSION_COOKIE
  68
+        session_cookie = self.COOKIES.get(AUTH_SESSION_COOKIE, '')
  69
+        try:
  70
+            self._session = sessions.get_session_from_cookie(session_cookie)
  71
+            self._user = self._session.get_user()
  72
+        except sessions.SessionDoesNotExist:
  73
+            from django.parts.auth import anonymoususers
  74
+            self._session = None
  75
+            self._user = anonymoususers.AnonymousUser()
  76
+
  77
+    def _get_session(self):
  78
+        if not hasattr(self, '_session'):
  79
+            self._load_session_and_user()
  80
+        return self._session
  81
+
  82
+    def _set_session(self, session):
  83
+        self._session = session
  84
+
  85
+    def _get_user(self):
  86
+        if not hasattr(self, '_user'):
  87
+            self._load_session_and_user()
  88
+        return self._user
  89
+
  90
+    def _set_user(self, user):
  91
+        self._user = user
  92
+
  93
+    GET = property(_get_get, _set_get)
  94
+    POST = property(_get_post, _set_post)
  95
+    COOKIES = property(_get_cookies, _set_cookies)
  96
+    FILES = property(_get_files)
  97
+    REQUEST = property(_get_request)
  98
+    session = property(_get_session, _set_session)
  99
+    user = property(_get_user, _set_user)
  100
+
  101
+class WSGIHandler:
  102
+    def __init__(self):
  103
+        self._request_middleware = self._view_middleware = self._response_middleware = None
  104
+
  105
+    def __call__(self, environ, start_response):
  106
+        from django.conf import settings
  107
+        from django.core import db
  108
+
  109
+        # Set up middleware if needed. We couldn't do this earlier, because
  110
+        # settings weren't available.
  111
+        if self._request_middleware is None:
  112
+            self.load_middleware()
  113
+
  114
+        try:
  115
+            request = WSGIRequest(environ)
  116
+            response = self.get_response(request.path, request)
  117
+        finally:
  118
+            db.db.close()
  119
+
  120
+        # Apply response middleware
  121
+        for middleware_method in self._response_middleware:
  122
+            response = middleware_method(request, response)
  123
+
  124
+        status = str(response.status_code) + ' ' # TODO: Extra space here is a hack.
  125
+        response_headers = response.headers
  126
+        if response.cookies:
  127
+            response_headers['Set-Cookie'] = response.cookies.output(header='')
  128
+        output = [response.get_content_as_string('utf-8')]
  129
+        start_response(status, response_headers.items())
  130
+        return output
  131
+
  132
+    def load_middleware(self):
  133
+        """
  134
+        Populate middleware lists from settings.MIDDLEWARE_CLASSES.
  135
+
  136
+        Must be called after the environment is fixed (see __call__).
  137
+        """
  138
+        from django.conf import settings
  139
+        from django.core import exceptions
  140
+        self._request_middleware = []
  141
+        self._view_middleware = []
  142
+        self._response_middleware = []
  143
+        for middleware_path in settings.MIDDLEWARE_CLASSES:
  144
+            dot = middleware_path.rindex('.')
  145
+            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
  146
+            try:
  147
+                mod = __import__(mw_module, '', '', [''])
  148
+            except ImportError, e:
  149
+                raise exceptions.ImproperlyConfigured, \
  150
+                    'Error importing middleware %s: "%s"' % (mw_module, e)
  151
+            try:
  152
+                mw_class = getattr(mod, mw_classname)
  153
+            except AttributeError:
  154
+                raise exceptions.ImproperlyConfigured, \
  155
+                    'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
  156
+
  157
+            try:
  158
+                mw_instance = mw_class()
  159
+            except exceptions.MiddlewareNotUsed:
  160
+                continue
  161
+
  162
+            if hasattr(mw_instance, 'process_request'):
  163
+                self._request_middleware.append(mw_instance.process_request)
  164
+            if hasattr(mw_instance, 'process_view'):
  165
+                self._view_middleware.append(mw_instance.process_view)
  166
+            if hasattr(mw_instance, 'process_response'):
  167
+                self._response_middleware.insert(0, mw_instance.process_response)
  168
+
  169
+    def get_response(self, path, request):
  170
+        "Returns an HttpResponse object for the given HttpRequest"
  171
+        from django.core import db, exceptions, urlresolvers
  172
+        from django.core.mail import mail_admins
  173
+        from django.conf.settings import DEBUG, INTERNAL_IPS, ROOT_URLCONF
  174
+
  175
+        # Apply request middleware
  176
+        for middleware_method in self._request_middleware:
  177
+            response = middleware_method(request)
  178
+            if response:
  179
+                return response
  180
+
  181
+        conf_module = __import__(ROOT_URLCONF, '', '', [''])
  182
+        resolver = urlresolvers.RegexURLResolver(conf_module.urlpatterns)
  183
+        try:
  184
+            callback, param_dict = resolver.resolve(path)
  185
+            # Apply view middleware
  186
+            for middleware_method in self._view_middleware:
  187
+                response = middleware_method(request, callback, param_dict)
  188
+                if response:
  189
+                    return response
  190
+            return callback(request, **param_dict)
  191
+        except exceptions.Http404:
  192
+            if DEBUG:
  193
+                return self.get_technical_error_response(is404=True)
  194
+            else:
  195
+                resolver = urlresolvers.Error404Resolver(conf_module.handler404)
  196
+                callback, param_dict = resolver.resolve()
  197
+                return callback(request, **param_dict)
  198
+        except db.DatabaseError:
  199
+            db.db.rollback()
  200
+            if DEBUG:
  201
+                return self.get_technical_error_response()
  202
+            else:
  203
+                subject = 'Database error (%s IP)' % \
  204
+                    (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
  205
+                message = "%s\n\n%s" % (self._get_traceback(), request)
  206
+                mail_admins(subject, message, fail_silently=True)
  207
+                return self.get_friendly_error_response(request, conf_module)
  208
+        except exceptions.PermissionDenied:
  209
+            return httpwrappers.HttpResponseForbidden('<h1>Permission denied</h1>')
  210
+        except: # Handle everything else, including SuspiciousOperation, etc.
  211
+            if DEBUG:
  212
+                return self.get_technical_error_response()
  213
+            else:
  214
+                subject = 'Coding error (%s IP)' % \
  215
+                    (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
  216
+                message = "%s\n\n%s" % (self._get_traceback(), request)
  217
+                mail_admins(subject, message, fail_silently=True)
  218
+                return self.get_friendly_error_response(request, conf_module)
  219
+
  220
+    def get_friendly_error_response(self, request, conf_module):
  221
+        """
  222
+        Returns an HttpResponse that displays a PUBLIC error message for a
  223
+        fundamental database or coding error.
  224
+        """
  225
+        from django.core import urlresolvers
  226
+        resolver = urlresolvers.Error404Resolver(conf_module.handler500)
  227
+        callback, param_dict = resolver.resolve()
  228
+        return callback(request, **param_dict)
  229
+
  230
+    def get_technical_error_response(self, is404=False):
  231
+        """
  232
+        Returns an HttpResponse that displays a TECHNICAL error message for a
  233
+        fundamental database or coding error.
  234
+        """
  235
+        error_string = "<pre>There's been an error:\n\n%s</pre>" % self._get_traceback()
  236
+        responseClass = is404 and httpwrappers.HttpResponseNotFound or httpwrappers.HttpResponseServerError
  237
+        return responseClass(error_string)
  238
+
  239
+    def _get_traceback(self):
  240
+        "Helper function to return the traceback as a string"
  241
+        import sys, traceback
  242
+        return '\n'.join(traceback.format_exception(*sys.exc_info()))
129  django/utils/httpwrappers.py
@@ -24,124 +24,6 @@ def __getitem__(self, key):
24 24
     def get_full_path(self):
25 25
         return ''
26 26
 
27  
-class ModPythonRequest(HttpRequest):
28  
-    def __init__(self, req):
29  
-        self._req = req
30  
-        self.path = req.uri
31  
-
32  
-    def __repr__(self):
33  
-        return '<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s,\nuser:%s>' % \
34  
-            (self.path, pformat(self.GET), pformat(self.POST), pformat(self.COOKIES),
35  
-            pformat(self.META), pformat(self.user))
36  
-
37  
-    def get_full_path(self):
38  
-        return '%s%s' % (self.path, self._req.args and ('?' + self._req.args) or '')
39  
-
40  
-    def _load_post_and_files(self):
41  
-        "Populates self._post and self._files"
42  
-        if self._req.headers_in.has_key('content-type') and self._req.headers_in['content-type'].startswith('multipart'):
43  
-            self._post, self._files = parse_file_upload(self._req.headers_in, self._req.read())
44  
-        else:
45  
-            self._post, self._files = QueryDict(self._req.read()), datastructures.MultiValueDict()
46  
-
47  
-    def _get_request(self):
48  
-        if not hasattr(self, '_request'):
49  
-           self._request = datastructures.MergeDict(self.POST, self.GET)
50  
-        return self._request
51  
-
52  
-    def _get_get(self):
53  
-        if not hasattr(self, '_get'):
54  
-            self._get = QueryDict(self._req.args)
55  
-        return self._get
56  
-
57  
-    def _set_get(self, get):
58  
-        self._get = get
59  
-
60  
-    def _get_post(self):
61  
-        if not hasattr(self, '_post'):
62  
-            self._load_post_and_files()
63  
-        return self._post
64  
-
65  
-    def _set_post(self, post):
66  
-        self._post = post
67  
-
68  
-    def _get_cookies(self):
69  
-        if not hasattr(self, '_cookies'):
70  
-            self._cookies = parse_cookie(self._req.headers_in.get('cookie', ''))
71  
-        return self._cookies
72  
-
73  
-    def _set_cookies(self, cookies):
74  
-        self._cookies = cookies
75  
-
76  
-    def _get_files(self):
77  
-        if not hasattr(self, '_files'):
78  
-            self._load_post_and_files()
79  
-        return self._files
80  
-
81  
-    def _get_meta(self):
82  
-        "Lazy loader that returns self.META dictionary"
83  
-        if not hasattr(self, '_meta'):
84  
-            self._meta = {
85  
-                'AUTH_TYPE':         self._req.ap_auth_type,
86  
-                'CONTENT_LENGTH':    self._req.clength, # This may be wrong
87  
-                'CONTENT_TYPE':      self._req.content_type, # This may be wrong
88  
-                'GATEWAY_INTERFACE': 'CGI/1.1',
89  
-                'PATH_INFO':         self._req.path_info,
90  
-                'PATH_TRANSLATED':   None, # Not supported
91  
-                'QUERY_STRING':      self._req.args,
92  
-                'REMOTE_ADDR':       self._req.connection.remote_ip,
93  
-                'REMOTE_HOST':       None, # DNS lookups not supported
94  
-                'REMOTE_IDENT':      self._req.connection.remote_logname,
95  
-                'REMOTE_USER':       self._req.user,
96  
-                'REQUEST_METHOD':    self._req.method,
97  
-                'SCRIPT_NAME':       None, # Not supported
98  
-                'SERVER_NAME':       self._req.server.server_hostname,
99  
-                'SERVER_PORT':       self._req.server.port,
100  
-                'SERVER_PROTOCOL':   self._req.protocol,
101  
-                'SERVER_SOFTWARE':   'mod_python'
102  
-            }
103  
-            for key, value in self._req.headers_in.items():
104  
-                key = 'HTTP_' + key.upper().replace('-', '_')
105  
-                self._meta[key] = value
106  
-        return self._meta
107  
-
108  
-    def _load_session_and_user(self):
109  
-        from django.models.auth import sessions
110  
-        from django.conf.settings import AUTH_SESSION_COOKIE
111  
-        session_cookie = self.COOKIES.get(AUTH_SESSION_COOKIE, '')
112  
-        try:
113  
-            self._session = sessions.get_session_from_cookie(session_cookie)
114  
-            self._user = self._session.get_user()
115  
-        except sessions.SessionDoesNotExist:
116  
-            from django.parts.auth import anonymoususers
117  
-            self._session = None
118  
-            self._user = anonymoususers.AnonymousUser()
119  
-
120  
-    def _get_session(self):
121  
-        if not hasattr(self, '_session'):
122  
-            self._load_session_and_user()
123  
-        return self._session
124  
-
125  
-    def _set_session(self, session):
126  
-        self._session = session
127  
-
128  
-    def _get_user(self):
129  
-        if not hasattr(self, '_user'):
130  
-            self._load_session_and_user()
131  
-        return self._user
132  
-
133  
-    def _set_user(self, user):
134  
-        self._user = user
135  
-
136  
-    GET = property(_get_get, _set_get)
137  
-    POST = property(_get_post, _set_post)
138  
-    COOKIES = property(_get_cookies, _set_cookies)
139  
-    FILES = property(_get_files)
140  
-    META = property(_get_meta)
141  
-    REQUEST = property(_get_request)
142  
-    session = property(_get_session, _set_session)
143  
-    user = property(_get_user, _set_user)
144  
-
145 27
 def parse_file_upload(header_dict, post_data):
146 28
     "Returns a tuple of (POST MultiValueDict, FILES MultiValueDict)"
147 29
     import email, email.Message
@@ -336,14 +218,3 @@ class HttpResponseServerError(HttpResponse):
336 218
     def __init__(self, content='', mimetype=DEFAULT_MIME_TYPE):
337 219
         HttpResponse.__init__(self, content, mimetype)
338 220
         self.status_code = 500
339  
-
340  
-def populate_apache_request(http_response, mod_python_req):
341  
-    "Populates the mod_python request object with an HttpResponse"
342  
-    mod_python_req.content_type = http_response['Content-Type'] or DEFAULT_MIME_TYPE
343  
-    del http_response['Content-Type']
344  
-    if http_response.cookies:
345  
-        mod_python_req.headers_out['Set-Cookie'] = http_response.cookies.output(header='')
346  
-    for key, value in http_response.headers.items():
347  
-        mod_python_req.headers_out[key] = value
348  
-    mod_python_req.status = http_response.status_code
349  
-    mod_python_req.write(http_response.get_content_as_string('utf-8'))

0 notes on commit ca3d89b

Please sign in to comment.
Something went wrong with that request. Please try again.