[Fixed]-Is Django middleware thread safe?

30👍

Why not bind your variable to the request object, like so:

class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        request.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        #... do something with request.thread_safe_variable here ...

10👍

No, very definitely not. I write about this issue here – the upshot is that storing state in a middleware class is a very bad idea.

As Steve points out, the solution is to add it to the request instead.

1👍

If you’re using mod_wsgi in daemon mode with multiple threads, none of these options will work.

WSGIDaemonProcess domain.com user=www-data group=www-data threads=2

This is tricky because it will work with the django dev server (single, local thread) and give unpredictable results in production depending on your thread’s lifetime.

Neither setting the request attribute nor manipulating the session is threadsafe under mod_wsgi. Since process_response takes the request as an argument, you should perform all of your logic in that function.

class ThreadsafeTestMiddleware(object):

    def process_response(self, request, response):
        thread_safe_variable = request.some_dynamic_value_from_request

Leave a comment