lundi 1 janvier 2018

Flask: how to serve an updating log file line by line?

There are two threads in my Python program, one is for flask, and the other one is for the background task and it will dynamically generate some logs strings into a log file when it is running.

I've tried streaming the file with yield like this:

@app.route('/task_status')
def get_background_task_log():
    def read_task_log():

        # Try load log files
        log_file = open("/tmp/task_log.log", "r")

        # Stream file to the client
        while True:
            new_line = log_file.readline()

            # Stream the file to the client until it ends.
            if "Foo: process finished!" in new_line:
                yield new_line.encode("utf-8")  # Flush the last line
                break

            yield new_line.encode("utf-8")

    return Response(read_task_log(), mimetype="text/plain",
                    headers={"Content-Disposition": "inline; filename=flashrom.log"})

But when Chrome loads /task_status, it just hangs there and wait until the line Foo: process finished come out, instead of show me the content line by line. I've also tried removing the Content-Disposition header and it stays the same.

Meanwhile I've also tried using send_file() but it can only returns a partial log file when I access it from Chrome.

What should I do then?




Aucun commentaire:

Enregistrer un commentaire