Search code examples
pythonflaskwaitsleep

time.sleep, Flask and I/O wait


When using time.sleep(), will a Flask request be blocked?

One of my Flask endpoint launches a long processing subtask, and in some cases, instead of doing the work asynchronously, it is possible to wait for the completion of the task and return the result in the same request.

In this case, my Flask app starts the process, then waits for it to complete before returning the result. My issue here, is that while calling something like (simplified):

while True:
    if process_is_done():
        break

    time.sleep(1)

Will Flask will block that request until it is done, or will it allow for other requests to come in the meantime?


Solution

  • Yes, that request is entirely blocked. time.sleep() does not inform anything of the sleep, it just 'idles' the CPU for the duration.

    Flask is itself not asynchronous, it has no concept of putting a request handler on hold and giving other requests more time. A good WSGI server will use threads and or multiple worker processes to achieve concurrency, but this one request is blocked and taking up CPU time all the same.