Index: django/core/handlers/base.py
===================================================================
--- django/core/handlers/base.py	(revision 8219)
+++ django/core/handlers/base.py	(working copy)
@@ -1,4 +1,8 @@
 import sys
+try:
+    set
+except NameError:
+    from sets import Set as set
 
 from django import http
 from django.core import signals
@@ -29,34 +33,45 @@
         self._view_middleware = []
         self._response_middleware = []
         self._exception_middleware = []
-        for middleware_path in settings.MIDDLEWARE_CLASSES:
-            try:
-                dot = middleware_path.rindex('.')
-            except ValueError:
-                raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
-            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
-            try:
-                mod = __import__(mw_module, {}, {}, [''])
-            except ImportError, e:
-                raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
-            try:
-                mw_class = getattr(mod, mw_classname)
-            except AttributeError:
-                raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
 
-            try:
-                mw_instance = mw_class()
-            except exceptions.MiddlewareNotUsed:
-                continue
+        if not settings.MIDDLEWARE_CLASSES:
+            return
 
+        # (middleware_path, weight) tuples in MIDDLEWARE_CLASSES,
+        # heavier items processed first in outbound methods
+        # OR just backwards-compatible strings
+        middleware_list = None
+        if isinstance(settings.MIDDLEWARE_CLASSES[0], tuple):
+            # uniqueness test
+            key_set = list(set([mw[1] for mw in settings.MIDDLEWARE_CLASSES]))
+            if len(key_set) != len(settings.MIDDLEWARE_CLASSES):
+                raise ImproperlyConfigured("Middleware outbound ordering "
+                        "values have to be unique.")
+
+            middleware_list = _middleware_list_from_iterable([(mw[1], mw[0])
+                for mw in settings.MIDDLEWARE_CLASSES])
+        else:
+            middleware_list = _middleware_list_from_iterable(enumerate(
+                settings.MIDDLEWARE_CLASSES))
+
+        if not middleware_list:
+            return
+
+        # inbound
+        for _, mw_instance in middleware_list:
             if hasattr(mw_instance, 'process_request'):
                 self._request_middleware.append(mw_instance.process_request)
             if hasattr(mw_instance, 'process_view'):
                 self._view_middleware.append(mw_instance.process_view)
+
+        # outbound
+        middleware_list.sort()
+        middleware_list.reverse()
+        for _, mw_instance in middleware_list:
             if hasattr(mw_instance, 'process_response'):
-                self._response_middleware.insert(0, mw_instance.process_response)
+                self._response_middleware.append(mw_instance.process_response)
             if hasattr(mw_instance, 'process_exception'):
-                self._exception_middleware.insert(0, mw_instance.process_exception)
+                self._exception_middleware.append(mw_instance.process_exception)
 
     def get_response(self, request):
         "Returns an HttpResponse object for the given HttpRequest"
@@ -196,3 +211,28 @@
         return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))])
     return force_unicode(environ.get('SCRIPT_NAME', u''))
 
+def _middleware_list_from_iterable(middleware_iterable):
+    middleware_list = []
+    for middleware_tuple in middleware_iterable:
+        middleware_path = middleware_tuple[1]
+        try:
+            dot = middleware_path.rindex('.')
+        except ValueError:
+            raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
+        mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
+        try:
+            mod = __import__(mw_module, {}, {}, [''])
+        except ImportError, e:
+            raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
+        try:
+            mw_class = getattr(mod, mw_classname)
+        except AttributeError:
+            raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
+
+        try:
+            mw_instance = mw_class()
+        except exceptions.MiddlewareNotUsed:
+            continue
+        middleware_list.append((middleware_tuple[0], mw_instance))
+    return middleware_list
+
