1

I need to modify response object in middleware, so i have added 'myproject.common.middlware.ResponseMiddleware'

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',  # order matters don't move
'django.middleware.gzip.GZipMiddleware',  # order matters don't move
'django.middleware.locale.LocaleMiddleware',  # order matters don't move
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'myproject.common.middleware.ResponseMiddleware',

)

However in my ResponseMiddleware, I have the code below:

class ResponseMiddleware(object):
    def process_response(self, request, response):
        if 'status_code' not in response:
            response['status_code'] = 200
        return response

However, response.status_code cannot be found in other middlewares such as django's CommonMiddleware. I use Django 1.4 and from the document, order to process_response is reversed order of the order defined in MIDDLEWARE_CLASSES. So I put mine to the very bottom.

and i get

AttributeError: 'dict' object has no attribute 'status_code' from other Middleware.

(*** this is related to WebSocket generates error in django common middleware)

Community
  • 1
  • 1
CIF
  • 1,754
  • 2
  • 18
  • 30

1 Answers1

1

The problem is that your middleware is being executed the first one with process_response.

process_request and process_view methods are executed from the top to the bottom of the list, but process_response is executed from the bottom to the top. Check the following graph from Django documentation:

https://docs.djangoproject.com/en/dev/topics/http/middleware/#hooks-and-application-order

So, if you put your middleware the first on the list, it should work.

pyriku
  • 1,251
  • 7
  • 17
  • I originally had it on very top but no luck. And my middleware has only process_response, so shouldn't i be putting it very bottom? Thanks. – CIF Mar 04 '13 at 17:38
  • Even if it only has `process_response`, if you want it to be the last one executed should be the first on the list according with the documentation. The test is simple: create another middleware, and play with both of them for see which one is executed first. – pyriku Mar 05 '13 at 09:00
  • For regular http request, it executes fine as expected. Still not sure (on testing) but this only doesn't work for WebSocket action. http://stackoverflow.com/questions/14364441/websocket-generates-error-in-django-common-middleware – CIF Mar 07 '13 at 17:39