I have a python function that calls many services, and prints results of the services called in a log file. this is my code :
def coordinator():
f = file(path,'a')
sys.stdout = f
/* do a lot of stuff */
f.close()
with open(path) as log:
logs = log.read()
return jsonify(log = logs)
The result of the function is returned to a jQuery getJSON function that displays the final log file in a web page :
$.getJSON('/../coordinator',
{//parameters},
function(data) {
//display data.log
}
);
My problem is that the user gets to see the log file only when the execution is finished. Is there a way to display logs as they are written in real time??
Python's stdout
is buffered, so it won't write until the buffer is full. To force an immediate write, use sys.stdout.flush()
, or f.flush()
in the case of your code.
I finally found what I was looking for here :
http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent
So basically I created a WebSocket between the Back-end (Python/Flask) and the Front-end (HTML, jquery) to ensure continuous communication.
And with Python I created a Thread that runs asynchronously with the Master thread, fetches repetitively the content of the log file and sends them to Jquery via ajax
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.