1

I am sending input data from a web page via AJAX request to a Flask app. During the time my Flask app processes this data I want to notify a user about what is going on. If it were a console script I would just print() this messages out, ie:

Parsing file A ...
Parsing file B ...

But how to dynamically push data from Flask to the web browser not causing page reloading and initiate this process from the server side? I believe I cant use json as a response to an AJAX call since this response is done once and I want to pass the notifying messages on their time.

Roman Dodin
  • 145
  • 1
  • 8

1 Answers1

1

The answer to your problems: Flask Streaming

Your route should look something like this:

from flask import stream_with_context, request, Response
from werkzeug import secure_filename

@app.route('/post_files')
def parse_files():
    def generate():
        for file in request.files['file']:
            filename = secure_filename(file.filename)
            yield 'Parsing file ' + filename + ' ...\n'
            parse_file(file) #your external parsing method
    return Response(stream_with_context(generate()))
Snuggert
  • 165
  • 7
  • Thanks, Snuggert. And in this case how to constantly populate a text-area or div with this approach? I saw examples for Server Send Events and send_template, but none of them were about simple `stream_with_context` or pure `Response` – Roman Dodin Apr 26 '16 at 18:21