Flask Enable streaming from flask


Example

Flask has that feature which lets you stream data from a view by using generators.

Let's change the app.py file

  • add from flask import Response
  • add from datetime import datetime
  • add from time import sleep
  • create a new view:
@app.route("/time/")
def time():
    def streamer():
        while True:
            yield "<p>{}</p>".format(datetime.now())
            sleep(1)

    return Response(streamer())

Now open your browser at localhost/time/. The site will load forever because nginx waits until the response is complete. In this case the response will never be complete because it will send the current date and time forever.

To prevent nginx from waiting we need to add a new line to the configuration.

Edit /etc/nginx/sites-available/flaskconfig

server {
    listen 80;
    server_name localhost;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/flask.sock;
        uwsgi_buffering off;  # <-- this line is new
    }
}

The line uwsgi_buffering off; tells nginx not to wait until a response it complete.

Restart nginx: sudo service nginx restart and look at localhost/time/ again.

Now you will see that every second a new line pops up.