Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #63 -- Refactored django.core.handlers into subclasses to remov…

…e duplicate code

git-svn-id: http://code.djangoproject.com/svn/django/trunk@298 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit c97efb6799168c8903fc1181ecada7fe9932dd1f 1 parent d573cb0
Adrian Holovaty authored July 22, 2005
117  django/core/handlers/base.py
... ...
@@ -0,0 +1,117 @@
  1
+from django.utils import httpwrappers
  2
+
  3
+class BaseHandler:
  4
+    def __init__(self):
  5
+        self._request_middleware = self._view_middleware = self._response_middleware = None
  6
+
  7
+    def load_middleware(self):
  8
+        """
  9
+        Populate middleware lists from settings.MIDDLEWARE_CLASSES.
  10
+
  11
+        Must be called after the environment is fixed (see __call__).
  12
+        """
  13
+        from django.conf import settings
  14
+        from django.core import exceptions
  15
+        self._request_middleware = []
  16
+        self._view_middleware = []
  17
+        self._response_middleware = []
  18
+        for middleware_path in settings.MIDDLEWARE_CLASSES:
  19
+            dot = middleware_path.rindex('.')
  20
+            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
  21
+            try:
  22
+                mod = __import__(mw_module, '', '', [''])
  23
+            except ImportError, e:
  24
+                raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
  25
+            try:
  26
+                mw_class = getattr(mod, mw_classname)
  27
+            except AttributeError:
  28
+                raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
  29
+
  30
+            try:
  31
+                mw_instance = mw_class()
  32
+            except exceptions.MiddlewareNotUsed:
  33
+                continue
  34
+
  35
+            if hasattr(mw_instance, 'process_request'):
  36
+                self._request_middleware.append(mw_instance.process_request)
  37
+            if hasattr(mw_instance, 'process_view'):
  38
+                self._view_middleware.append(mw_instance.process_view)
  39
+            if hasattr(mw_instance, 'process_response'):
  40
+                self._response_middleware.insert(0, mw_instance.process_response)
  41
+
  42
+    def get_response(self, path, request):
  43
+        "Returns an HttpResponse object for the given HttpRequest"
  44
+        from django.core import db, exceptions, urlresolvers
  45
+        from django.core.mail import mail_admins
  46
+        from django.conf.settings import DEBUG, INTERNAL_IPS, ROOT_URLCONF
  47
+
  48
+        # Apply request middleware
  49
+        for middleware_method in self._request_middleware:
  50
+            response = middleware_method(request)
  51
+            if response:
  52
+                return response
  53
+
  54
+        conf_module = __import__(ROOT_URLCONF, '', '', [''])
  55
+        resolver = urlresolvers.RegexURLResolver(conf_module.urlpatterns)
  56
+        try:
  57
+            callback, param_dict = resolver.resolve(path)
  58
+            # Apply view middleware
  59
+            for middleware_method in self._view_middleware:
  60
+                response = middleware_method(request, callback, param_dict)
  61
+                if response:
  62
+                    return response
  63
+            return callback(request, **param_dict)
  64
+        except exceptions.Http404:
  65
+            if DEBUG:
  66
+                return self.get_technical_error_response(is404=True)
  67
+            else:
  68
+                resolver = urlresolvers.Error404Resolver(conf_module.handler404)
  69
+                callback, param_dict = resolver.resolve()
  70
+                return callback(request, **param_dict)
  71
+        except db.DatabaseError:
  72
+            db.db.rollback()
  73
+            if DEBUG:
  74
+                return self.get_technical_error_response()
  75
+            else:
  76
+                subject = 'Database error (%s IP)' % (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
  77
+                message = "%s\n\n%s" % (self._get_traceback(), request)
  78
+                mail_admins(subject, message, fail_silently=True)
  79
+                return self.get_friendly_error_response(request, conf_module)
  80
+        except exceptions.PermissionDenied:
  81
+            return httpwrappers.HttpResponseForbidden('<h1>Permission denied</h1>')
  82
+        except: # Handle everything else, including SuspiciousOperation, etc.
  83
+            if DEBUG:
  84
+                return self.get_technical_error_response()
  85
+            else:
  86
+                subject = 'Coding error (%s IP)' % (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
  87
+                try:
  88
+                    request_repr = repr(request)
  89
+                except:
  90
+                    request_repr = "Request repr() unavailable"
  91
+                message = "%s\n\n%s" % (self._get_traceback(), request_repr)
  92
+                mail_admins(subject, message, fail_silently=True)
  93
+                return self.get_friendly_error_response(request, conf_module)
  94
+
  95
+    def get_friendly_error_response(self, request, conf_module):
  96
+        """
  97
+        Returns an HttpResponse that displays a PUBLIC error message for a
  98
+        fundamental database or coding error.
  99
+        """
  100
+        from django.core import urlresolvers
  101
+        resolver = urlresolvers.Error404Resolver(conf_module.handler500)
  102
+        callback, param_dict = resolver.resolve()
  103
+        return callback(request, **param_dict)
  104
+
  105
+    def get_technical_error_response(self, is404=False):
  106
+        """
  107
+        Returns an HttpResponse that displays a TECHNICAL error message for a
  108
+        fundamental database or coding error.
  109
+        """
  110
+        error_string = "There's been an error:\n\n%s" % self._get_traceback()
  111
+        responseClass = is404 and httpwrappers.HttpResponseNotFound or httpwrappers.HttpResponseServerError
  112
+        return responseClass(error_string, mimetype='text/plain')
  113
+
  114
+    def _get_traceback(self):
  115
+        "Helper function to return the traceback as a string"
  116
+        import sys, traceback
  117
+        return '\n'.join(traceback.format_exception(*sys.exc_info()))
118  django/core/handlers/modpython.py
... ...
@@ -1,3 +1,4 @@
  1
+from django.core.handlers.base import BaseHandler
1 2
 from django.utils import datastructures, httpwrappers
2 3
 from pprint import pformat
3 4
 import os
@@ -124,10 +125,7 @@ def _set_user(self, user):
124 125
     session = property(_get_session, _set_session)
125 126
     user = property(_get_user, _set_user)
126 127
 
127  
-class ModPythonHandler:
128  
-    def __init__(self):
129  
-        self._request_middleware = self._view_middleware = self._response_middleware = None
130  
-
  128
+class ModPythonHandler(BaseHandler):
131 129
     def __call__(self, req):
132 130
         # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes that
133 131
         os.environ.update(req.subprocess_env)
@@ -155,118 +153,6 @@ def __call__(self, req):
155 153
         populate_apache_request(response, req)
156 154
         return 0 # mod_python.apache.OK
157 155
 
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  
-                try:
239  
-                    request_repr = repr(request)
240  
-                except:
241  
-                    request_repr = "Request repr() unavailable"
242  
-                message = "%s\n\n%s" % (self._get_traceback(), request_repr)
243  
-                mail_admins(subject, message, fail_silently=True)
244  
-                return self.get_friendly_error_response(request, conf_module)
245  
-
246  
-    def get_friendly_error_response(self, request, conf_module):
247  
-        """
248  
-        Returns an HttpResponse that displays a PUBLIC error message for a
249  
-        fundamental database or coding error.
250  
-        """
251  
-        from django.core import urlresolvers
252  
-        resolver = urlresolvers.Error404Resolver(conf_module.handler500)
253  
-        callback, param_dict = resolver.resolve()
254  
-        return callback(request, **param_dict)
255  
-
256  
-    def get_technical_error_response(self, is404=False):
257  
-        """
258  
-        Returns an HttpResponse that displays a TECHNICAL error message for a
259  
-        fundamental database or coding error.
260  
-        """
261  
-        error_string = "There's been an error:\n\n%s" % self._get_traceback()
262  
-        responseClass = is404 and httpwrappers.HttpResponseNotFound or httpwrappers.HttpResponseServerError
263  
-        return responseClass(error_string, mimetype='text/plain')
264  
-
265  
-    def _get_traceback(self):
266  
-        "Helper function to return the traceback as a string"
267  
-        import sys, traceback
268  
-        return '\n'.join(traceback.format_exception(*sys.exc_info()))
269  
-
270 156
 def populate_apache_request(http_response, mod_python_req):
271 157
     "Populates the mod_python request object with an HttpResponse"
272 158
     mod_python_req.content_type = http_response['Content-Type'] or httpwrappers.DEFAULT_MIME_TYPE
118  django/core/handlers/wsgi.py
... ...
@@ -1,3 +1,4 @@
  1
+from django.core.handlers.base import BaseHandler
1 2
 from django.utils import datastructures, httpwrappers
2 3
 from pprint import pformat
3 4
 
@@ -104,10 +105,7 @@ def _set_user(self, user):
104 105
     session = property(_get_session, _set_session)
105 106
     user = property(_get_user, _set_user)
106 107
 
107  
-class WSGIHandler:
108  
-    def __init__(self):
109  
-        self._request_middleware = self._view_middleware = self._response_middleware = None
110  
-
  108
+class WSGIHandler(BaseHandler):
111 109
     def __call__(self, environ, start_response):
112 110
         from django.conf import settings
113 111
         from django.core import db
@@ -139,118 +137,6 @@ def __call__(self, environ, start_response):
139 137
         start_response(status, response_headers.items())
140 138
         return output
141 139
 
142  
-    def load_middleware(self):
143  
-        """
144  
-        Populate middleware lists from settings.MIDDLEWARE_CLASSES.
145  
-
146  
-        Must be called after the environment is fixed (see __call__).
147  
-        """
148  
-        from django.conf import settings
149  
-        from django.core import exceptions
150  
-        self._request_middleware = []
151  
-        self._view_middleware = []
152  
-        self._response_middleware = []
153  
-        for middleware_path in settings.MIDDLEWARE_CLASSES:
154  
-            dot = middleware_path.rindex('.')
155  
-            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
156  
-            try:
157  
-                mod = __import__(mw_module, '', '', [''])
158  
-            except ImportError, e:
159  
-                raise exceptions.ImproperlyConfigured, \
160  
-                    'Error importing middleware %s: "%s"' % (mw_module, e)
161  
-            try:
162  
-                mw_class = getattr(mod, mw_classname)
163  
-            except AttributeError:
164  
-                raise exceptions.ImproperlyConfigured, \
165  
-                    'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
166  
-
167  
-            try:
168  
-                mw_instance = mw_class()
169  
-            except exceptions.MiddlewareNotUsed:
170  
-                continue
171  
-
172  
-            if hasattr(mw_instance, 'process_request'):
173  
-                self._request_middleware.append(mw_instance.process_request)
174  
-            if hasattr(mw_instance, 'process_view'):
175  
-                self._view_middleware.append(mw_instance.process_view)
176  
-            if hasattr(mw_instance, 'process_response'):
177  
-                self._response_middleware.insert(0, mw_instance.process_response)
178  
-
179  
-    def get_response(self, path, request):
180  
-        "Returns an HttpResponse object for the given HttpRequest"
181  
-        from django.core import db, exceptions, urlresolvers
182  
-        from django.core.mail import mail_admins
183  
-        from django.conf.settings import DEBUG, INTERNAL_IPS, ROOT_URLCONF
184  
-
185  
-        # Apply request middleware
186  
-        for middleware_method in self._request_middleware:
187  
-            response = middleware_method(request)
188  
-            if response:
189  
-                return response
190  
-
191  
-        conf_module = __import__(ROOT_URLCONF, '', '', [''])
192  
-        resolver = urlresolvers.RegexURLResolver(conf_module.urlpatterns)
193  
-        try:
194  
-            callback, param_dict = resolver.resolve(path)
195  
-            # Apply view middleware
196  
-            for middleware_method in self._view_middleware:
197  
-                response = middleware_method(request, callback, param_dict)
198  
-                if response:
199  
-                    return response
200  
-            return callback(request, **param_dict)
201  
-        except exceptions.Http404:
202  
-            if DEBUG:
203  
-                return self.get_technical_error_response(is404=True)
204  
-            else:
205  
-                resolver = urlresolvers.Error404Resolver(conf_module.handler404)
206  
-                callback, param_dict = resolver.resolve()
207  
-                return callback(request, **param_dict)
208  
-        except db.DatabaseError:
209  
-            db.db.rollback()
210  
-            if DEBUG:
211  
-                return self.get_technical_error_response()
212  
-            else:
213  
-                subject = 'Database error (%s IP)' % \
214  
-                    (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
215  
-                message = "%s\n\n%s" % (self._get_traceback(), request)
216  
-                mail_admins(subject, message, fail_silently=True)
217  
-                return self.get_friendly_error_response(request, conf_module)
218  
-        except exceptions.PermissionDenied:
219  
-            return httpwrappers.HttpResponseForbidden('<h1>Permission denied</h1>')
220  
-        except: # Handle everything else, including SuspiciousOperation, etc.
221  
-            if DEBUG:
222  
-                return self.get_technical_error_response()
223  
-            else:
224  
-                subject = 'Coding error (%s IP)' % \
225  
-                    (request.META['REMOTE_ADDR'] in INTERNAL_IPS and 'internal' or 'EXTERNAL')
226  
-                message = "%s\n\n%s" % (self._get_traceback(), request)
227  
-                mail_admins(subject, message, fail_silently=True)
228  
-                return self.get_friendly_error_response(request, conf_module)
229  
-
230  
-    def get_friendly_error_response(self, request, conf_module):
231  
-        """
232  
-        Returns an HttpResponse that displays a PUBLIC error message for a
233  
-        fundamental database or coding error.
234  
-        """
235  
-        from django.core import urlresolvers
236  
-        resolver = urlresolvers.Error404Resolver(conf_module.handler500)
237  
-        callback, param_dict = resolver.resolve()
238  
-        return callback(request, **param_dict)
239  
-
240  
-    def get_technical_error_response(self, is404=False):
241  
-        """
242  
-        Returns an HttpResponse that displays a TECHNICAL error message for a
243  
-        fundamental database or coding error.
244  
-        """
245  
-        error_string = "There's been an error:\n\n%s" % self._get_traceback()
246  
-        responseClass = is404 and httpwrappers.HttpResponseNotFound or httpwrappers.HttpResponseServerError
247  
-        return responseClass(error_string, mimetype='text/plain')
248  
-
249  
-    def _get_traceback(self):
250  
-        "Helper function to return the traceback as a string"
251  
-        import sys, traceback
252  
-        return '\n'.join(traceback.format_exception(*sys.exc_info()))
253  
-
254 140
 class AdminMediaHandler:
255 141
     """
256 142
     WSGI middleware that intercepts calls to the admin media directory, as

0 notes on commit c97efb6

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