Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow Requests on Local Flask Server

Tags:

python

flask

Just starting to play around with Flask on a local server and I'm noticing the request/response times are way slower than I feel they should be.

Just a simple server like the following takes close to 5 seconds to respond.

from flask import Flask  app = Flask(__name__)  @app.route("/") def index():     return "index"  if __name__ == "__main__":     app.run() 

Any ideas? Or is this just how the local server is?

like image 201
Meroon Avatar asked Jun 22 '12 04:06

Meroon


People also ask

Why is my Flask app so slow?

When Flask app runs slow we need to identify what is the bottleneck. It can be an overloaded database, unresponsive external API, or heavy, CPU-intensive computation.

How many requests per second can Flask handle?

Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.

Can Flask server handle multiple 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).


2 Answers

Ok I figured it out. It appears to be an issue with Werkzeug and os's that support ipv6.

From the Werkzeug site http://werkzeug.pocoo.org/docs/serving/:

On operating systems that support ipv6 and have it configured such as modern Linux systems, OS X 10.4 or higher as well as Windows Vista some browsers can be painfully slow if accessing your local server. The reason for this is that sometimes “localhost” is configured to be available on both ipv4 and ipv6 socktes and some browsers will try to access ipv6 first and then ivp4.

So the fix is to disable ipv6 from the localhost by commenting out the following line from my hosts file:

::1             localhost  

Once I do this the latency problems go away.

I'm really digging Flask and I'm glad that it's not a problem with the framework. I knew it couldn't be.

like image 133
Meroon Avatar answered Sep 30 '22 03:09

Meroon


Add "threaded=True" as an argument to app.run(), as suggested here: http://arusahni.net/blog/2013/10/flask-multithreading.html

For example: app.run(host="0.0.0.0", port=8080, threaded=True)

The ipv6-disabling solution did not work for me, but this did.

like image 21
Sajid Siddiqi Avatar answered Sep 30 '22 02:09

Sajid Siddiqi