Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Flask requests concurrently with threaded=True

Tags:

python

flask

What exactly does passing threaded = True to app.run() do?

My application processes input from the user, and takes a bit of time to do so. During this time, the application is unable to handle other requests. I have tested my application with threaded=True and it allows me to handle multiple requests concurrently.

like image 961
Harrison Avatar asked Aug 10 '16 14:08

Harrison


People also ask

How do you handle concurrent request in Flask?

Flask applications are deployed on a web server, either the built-in server for development and testing or a suitable server (gunicorn, nginx etc.) for production. By default, the server can handle multiple client requests without the programmer having to do anything special in the application.

What does threaded true do in Flask?

With threaded=True requests are each handled in a new thread. How many threads your server can handle concurrently depends entirely on your OS and what limits it sets on the number of threads per process. The implementation uses the SocketServer.

How does Flask handle multiple concurrent requests?

The server component that comes with Flask is really only meant for when you are developing your application; even though it can be configured to handle concurrent requests with app. run(threaded=True) (as of Flask 1.0 this is the default).

Is Flask app single threaded?

As of Flask 1.0, flask server is multi-threaded by default. Each new request is handled in a new thread. This is a simple Flask application using default settings.


1 Answers

As of Flask 1.0, the WSGI server included with Flask is run in threaded mode by default.

Prior to 1.0, or if you disable threading, the server is run in single-threaded mode, and can only handle one request at a time. Any parallel requests will have to wait until they can be handled, which can lead to issues if you tried to contact your own server from a request.

With threaded=True requests are each handled in a new thread. How many threads your server can handle concurrently depends entirely on your OS and what limits it sets on the number of threads per process. The implementation uses the SocketServer.ThreadingMixIn class, which sets no limits to the number of threads it can spin up.

Note that the Flask server is designed for development only. It is not a production-ready server. Don't rely on it to run your site on the wider web. Use a proper WSGI server (like gunicorn or uWSGI) instead.

like image 143
Martijn Pieters Avatar answered Oct 28 '22 17:10

Martijn Pieters