16

Are Django middleware thread safe? Can I do something like this,

class ThreadsafeTestMiddleware(object):

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

    def process_response(self, request, response):
        # will self.thread_safe_variable always equal to some_dynamic_value_from_request?

3 Answers 3

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 ...
1
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
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
7
  • This is incorrect. Your request/response object is not shared between threads and/or requests so it is safe to use. Jan 9, 2014 at 15:18
  • Didn't work for me. I had cases where the first user's request data was being set for the lifetime of the thread and causing issues.
    – roktechie
    Jan 9, 2014 at 19:01
  • The request object is created at the start of a request and not disposed until the request has passed through all the middleware classes, been handled, and passed back through the middlewares again. It's nothing to do with threading - it's the same, unshared object the whole way through. Jan 16, 2014 at 20:22
  • Makes total sense, but this was broken and always stickied the first user's data. pastebin.com/zJ5wct3Z
    – roktechie
    Jan 17, 2014 at 0:48
  • It's your use of self.refcode = refcode that's incorrect here. Change it to request.refcode = refcode, then read it back from request.refcode in the process_response method. I hope that helps. Jan 18, 2014 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.