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?
Note that the Django ORM is explicitly thread-safe. There are multiple references in the documentation about threaded operation.
Node. js has a single threaded, non-blocking I/O mode of execution, while Django being a framework of Python, has a multi-threaded mode of execution.
Django itself does not determine whether it runs in one or more threads. This is the job of the server running Django. The development server used to be single-threaded, but in recent versions it has been made multithreaded.
No it is not currently thread safe.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With