10

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Frank Cheng
  • 5,928
  • 9
  • 52
  • 80
  • 3
    http://stackoverflow.com/questions/18430692/perform-task-directly-after-returning-json/18430861#18430861 – Arsh Singh Sep 24 '13 at 08:14
  • http://python-rq.org/ – zenpoy Sep 24 '13 at 15:04
  • 1
    _"Flask is a single thread web server."_ This is not correct. Flask is a framework, and has a function to help give you create a debug server. That [debug server can use multiple threads or processes](http://flask.pocoo.org/docs/api/#flask.Flask.run). _"I want when every client request to server, it always output "request" on console immediately.... but it still appears synchronous"_ What is the exact output you are getting? – Mark Hildreth Sep 26 '13 at 21:02

2 Answers2

1

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.

Markus Unterwaditzer
  • 7,992
  • 32
  • 60
  • From Flask-Celery page: «FROM CELERY 3.0 THIS LIBRARY IS NO LONGER NECESSARY, INSTEAD YOU SHOULD USE THE STANDARD CELERY API». Also you can check [this post](http://blog.miguelgrinberg.com/post/using-celery-with-flask) for details with Flask and Celery. – Ilya V. Schurov Nov 23 '15 at 19:14
1

I believe you are asking about something called "streaming". For Flask this can be accomplished using generator functions and the yield keyword.

Streaming is covered in more detail in the official Flask documentation, have a look here.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152