Friday 19 March 2021

Does Django use one thread to process several requests in WSGI or Gunicorn?

As per the title, I am wondering if Django, when run via WSGI or Gunicorn, uses one thread to process several requests?

I know it is a bad practice to access the request from places not meant to be accessed from, but I still want to do it. (for good reasons in my opinion, such as accessing the current user and site in my custom template loader. Django template loader doesn't offer these two entities.)

Now I managed to get access to the user, etc. from everywhere using the following bit of code:

import threading

_thread_locals = threading.local()

def get_current_request():
    return getattr(_thread_locals, "request", None)

class RequestThreadMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        _thread_locals.request = request
        response = self.get_response(request)
        return response

My question/concern is: is it guaranteed that requests/users don't get mixed up in production? I am concerned the second user, for instance, gets identified as the first user because the thread is being used for my than one request. Or, the request gets overwritten by another request while the original request hasn't finished yet. Is that possible, or every request has its own local thread in WSGI and Gunicorn?



from Does Django use one thread to process several requests in WSGI or Gunicorn?

No comments:

Post a Comment