Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make flask response to client asynchronously?

Flask is a single thread web server. But I want to make it won't block when handle some time consuming request.

For example:

from flask import Flask
import time
import sys
app = Flask(__name__)

@app.route("/")
def hello():
    print "request"
    sys.stdout.flush()
    for _ in range(10000000):
        for j in range(10000000):
            i = 1
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True)

I want when every client request to server, it always output "request" on console immediately. I have try gunicorn and run with gunicorn -k gevent -w 4 a:app but it still appears synchronous.

like image 393
Frank Cheng Avatar asked Sep 24 '13 07:09

Frank Cheng


People also ask

Is Flask synchronous or asynchronous?

Flask has been claimed as synchronous on many occasions, yet still possible to get async working but takes extra work.

Does Flask allow async?

Traditional Flask views will still be appropriate for most use cases, but Flask's async support enables writing and using code that wasn't possible natively before.

How do you make an API asynchronous in Python?

We can write asynchronous code with Python by using a library called Asyncio, though. Python has another library called Aiohttp that is an HTTP client and server based on Asyncio. Thus, we can use Asyncio to create asynchronous API calls. This is useful for optimizing code.

Why is Flask not async?

The simple explanation is that Flask uses WSGI to service HTTP requests and responses which doesn't support asynchronous I/O. Asynchronous code requires a running event loop to execute, so Flask needs to get a running event loop from somewhere in order to execute an async view.


1 Answers

This snippet is a good starting point.

You also should look into Celery or RQ, they're the right thing to use for larger projects, more importantly they're not Flask-specific.

They also have Flask integration each, Flask-Celery and Flask-RQ.

like image 188
Markus Unterwaditzer Avatar answered Oct 02 '22 03:10

Markus Unterwaditzer