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.
Flask has been claimed as synchronous on many occasions, yet still possible to get async working but takes extra work.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With