Ticket #730: middleware_ordering_with_path-weight_tuples.diff

File middleware_ordering_with_path-weight_tuples.diff, 2.2 KB (added by mrts, 16 years ago)

Note that the patch can be made backwards-compatible by adding additional isinstance(middleware, tuple) checks. Whether that is good remains open.

  • django/core/handlers/base.py

     
    2929        self._view_middleware = []
    3030        self._response_middleware = []
    3131        self._exception_middleware = []
    32         for middleware_path in settings.MIDDLEWARE_CLASSES:
     32        # (middleware_path, weight) tuples in MIDDLEWARE_CLASSES
     33        # heavier items processed first
     34        middleware_list = []
     35        for middleware in settings.MIDDLEWARE_CLASSES:
     36            middleware_path = middleware[0]
    3337            try:
    3438                dot = middleware_path.rindex('.')
    3539            except ValueError:
     
    4852                mw_instance = mw_class()
    4953            except exceptions.MiddlewareNotUsed:
    5054                continue
     55            middleware_list.append((middleware[1], mw_instance))
    5156
    52             if hasattr(mw_instance, 'process_request'):
     57        # inbound
     58        for middleware in middleware_list:
     59            if hasattr(middleware[1], 'process_request'):
    5360                self._request_middleware.append(mw_instance.process_request)
    54             if hasattr(mw_instance, 'process_view'):
     61            if hasattr(middleware[1], 'process_view'):
    5562                self._view_middleware.append(mw_instance.process_view)
    56             if hasattr(mw_instance, 'process_response'):
    57                 self._response_middleware.insert(0, mw_instance.process_response)
    58             if hasattr(mw_instance, 'process_exception'):
    59                 self._exception_middleware.insert(0, mw_instance.process_exception)
    6063
     64        # outbound
     65        middleware_list.sort()
     66        middleware_list.reverse() # remove if lighter items first
     67        for middleware in middleware_list:
     68            if hasattr(middleware[1], 'process_response'):
     69                self._response_middleware.append(0, mw_instance.process_response)
     70            if hasattr(middleware[1], 'process_exception'):
     71                self._exception_middleware.append(0, mw_instance.process_exception)
     72
    6173    def get_response(self, request):
    6274        "Returns an HttpResponse object for the given HttpRequest"
    6375        from django.core import exceptions, urlresolvers
Back to Top