Displaying a .txt file in my html using Python Flask

Maybe it would be better if for the log to read the file backwards in order to access the last log first.

pip3 install file-read-backwards

For example, I will show this code backwards:

In your case, it is necessary to replace app.py with logs.txt

from flask import Flask, render_template
from file_read_backwards import FileReadBackwards

app = Flask(__name__, template_folder="template")

with FileReadBackwards("app.py") as f:
    # getting lines by lines starting from the last line up
    b_lines = [ row for row in f ]

@app.route('/', methods=["GET", "POST"])
def index():
    return render_template('index.html', b_lines=b_lines)

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

UPDATE - without libraries

from flask import Flask, render_template

app = Flask(__name__, template_folder="template")

@app.route('/', methods=["GET", "POST"])
def index():
    b_lines = [row for row in reversed(list(open("app.py")))]
    return render_template('index.html', b_lines=b_lines)

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

Put in your log.html:

<br>
&nbsp;&nbsp;Description:
<br>
<textarea id="stackoverflow" name="stackoverflow_review" rows="35" cols="55">   
   {% for line in b_lines %}
      {{ line }}
   {% endfor %}
</textarea>

output:

enter image description here

In your case, the latest changes from the logs.txt file will be displayed first.


 return Response(content, mimetype='text/plain')

but really you probably want to use something like logstash...

Tags:

Python

Flask