Handling Multiple Requests on Flask

Flask is one of my favourite Python package. It’s simple, it’s lightweight and it’s easy. In short, Flask is awesome!

I was doing my routine business behind my desk when my coworker made a complain that he didn’t get the return from the API that I have developed. That’s weird because the last time I checked in the morning, everything was fine.

At first, I thought that the internet was down, but it’s not. I can access any sites I want. Next, I check the server’s log: yes, the script stopped working; without leaving any error messages.

Reproducing the errors

I restarted my Python script and asked my coworker show me how he got the problem. He easily managed to reproduce the error, leaving me scratching my head in confusion. There’s no error log in the server, it just stop working.

I came back to my coworker and asked what he did to make the script stop working. He just said that he sent multiple requests.

Got it!

Problem solving

Normally, Flask is run in single-threaded mode, and can only handle one request at a time, and any parallel requests should wait until they can be handled. Solving this problem is a quite easy work to do, you only need put threaded=True in your script so it will handle each requests in different thread. Your script should look like this:

app.run(host=HOST, port=PORT, threaded=True)

After I restarted my script, I asked my coworker to test the API once again and it turned out that everything worked. He got the return value he needed.

I didn’t hear any complain from him since then by the way.