Django Dev Server - sleep(N) in Middleware makes requests sleep multiple N seconds

139 Views Asked by At

Working on a middleware that slows down dev server response time. To simplify it I've created a very simple example that measures get_response time and then sleeps so the whole request cycle takes approximately 2 seconds.

The problem is that when there are multiple requests sent at once, some of them sleep 2xN time (not just a little bit longer, it's multiplicated).

I assume it's because of limits of Django's dev server concurrency. Is it possible to make it work?

class SnailMiddleware:
    """ Middleware that throttle responses """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest):
        start = now()
        response = self.get_response(request)
        elapsed_time = (now() - start).total_seconds()
        time.sleep(2 - elapsed_time)
        return response

These are the times:

enter image description here

Do you know where is the problem and how to make it work?

0

There are 0 best solutions below