How to make html view/template that updates with new data from changed file

本秂侑毒 提交于 2020-01-25 07:02:53

问题


So I have a basic function called "follow" that monitors for file changes. That function yields each new line that is added to that file. That part works well, at least from what I see when testing it with print function. Now, I want to display those new lines as table rows in HTML template.

This is my app main function:

import time
import json
from flask import Flask, render_template

app = Flask(__name__)


def follow(myfile):
    myfile.seek(0, 2)
    while True:
        new_line = myfile.readline()
        if not new_line:
            time.sleep(0.1)
            continue
        yield new_line


logfile = open("/files/myfile.log")
new_lines = follow(logfile)
raw_list = []


@app.route("/home")
def output_log():
    for new_line in new_lines:
        print(new_line)
        raw_list.append(new_line)
        result_list = json.dumps(raw_list)
        print(new_line)
        # return render_template("systemlog.html", results=result_list, mimetype='text/html')


if __name__ == "__main__":
app.run(debug=True)

I am using jinja templating and I managed to display data in table from static file, but how to do it when file has been constantly updated. Note that this will be "real time" monitoring.

As you can see, I've tried some desperate moves, including rendering file with each iteration inside for loop, from which I did not expected any stable results. Also I've seen that people use ajax for rendering dynamic content, but I can't wrap my head around how to do it when monitoring file this way.

Any suggestion is appreciated

来源:https://stackoverflow.com/questions/51109250/how-to-make-html-view-template-that-updates-with-new-data-from-changed-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!