I have a flask page that auto-updates from a log file:
@app.route('/console-refresh')
def refresh():
global previouscontent
previouscontent = ""
def generate_response():
global previouscontent
with open("logfile", "r") as f:
while True:
f.seek(0)
content = f.read()
if content.find(previouscontent) != 0:
yield "\b" * len(previouscontent)
previouscontent = ""
yield content[len(previouscontent):]
previouscontent = content
sleep(1)
return app.response_class(generate_response(), mimetype="text/plain")
The line yield "\b" * len(previouscontent)
is intended to clear the output.
With a print it works, but when I try to use it in my flask page, it shows this.
What is the HTML equivalent of \b
?
Else how do I clear the yield
output?
Thanks
Solution:
class RefreshHandler:
def __init__(self):
self.previous_content = ""
def generate_response(self):
while True:
with open("logfile", "r") as f:
content = f.read()
if content.find(self.previous_content) != 0:
yield '<meta http-equiv = "refresh" content = "0">'
return
yield content[len(self.previous_content):]
self.previous_content = content
sleep(1)
@app.route('/console-refresh')
def refresh():
return app.response_class(RefreshHandler().generate_response(), mimetype="text/html")
RefreshHandler().generate_response()
is where you add your yields.
Each time there is a yield string
, it is added to the output.
To restart from the beginnning, the block
yield '<meta http-equiv = "refresh" content = "0">'
return
will refresh the page on the client side and end the stream.
Unfortunately there is still a problem: How to add this to another html page without JavaScript?