Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Django middleware thread safe?

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?
like image 599
Deepan Avatar asked Jun 02 '11 12:06

Deepan


People also ask

Is Django thread safe?

Note that the Django ORM is explicitly thread-safe. There are multiple references in the documentation about threaded operation.

Does Django support multithreading?

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.

Is Django single threaded or multithreaded?

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.

Is Stringio thread safe?

No it is not currently thread safe.


2 Answers

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 ...
like image 121
Steve Mayne Avatar answered Sep 22 '22 20:09

Steve Mayne


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.

like image 27
Daniel Roseman Avatar answered Sep 21 '22 20:09

Daniel Roseman