Python Forum
Help with Python -> html - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help with Python -> html (/thread-34449.html)



Help with Python -> html - lukeyd - Aug-01-2021

Good afternoon

I'm quite new to Python and I am trying to get the result of a script to show into a html tag - so within my app.py I have the following code;

file = open("blocks.txt", "r")
line_count = 0
for line in file:
    if line != "\n":
        line_count += 1
file.close()

print(line_count)
Then within my index.html I put this;

  <b>IP's Blocked: <label>{{line_count}}</label></b>
As you can imagine, this mustn't be right. How can I get it to work ?


RE: Help with Python -> html - ndc85430 - Aug-01-2021

What? It looks like your index.html is a template (Jinja, or is it something else?), so where is the call to the template engine that takes the data and renders the template?

You need to show more code and explain what exactly isn't working and what you expect to happen.


RE: Help with Python -> html - lukeyd - Aug-01-2021

Sorry,

So the full app.py is this;

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

file = open("blocks.txt", "r")
line_count = 0
for line in file:
    if line != "\n":
        line_count += 1
file.close()

print(line_count)

if __name__ == "__main__":
    app.debug=True
    app.run()
The full index.html is this;

<!DOCTYPE html>
<title>Status Information</title>
<body>
    <center>
        <b>IP's Blocked: <label>{{line_count}}</label></b>
    </center>
</body>
I am wanting to show the total of the counted lines (from app.py) in the label shown in the index.html

I hope this makes sense ?


RE: Help with Python -> html - ndc85430 - Aug-01-2021

Lines 9-16 aren't part of the handler function, so how do you expect them to be executed when a request comes in? Also, the call to render_template on line 7 needs to pass the value for the variable line_count that's used in the template (you use keyword arguments to do so, as described in the docs).


RE: Help with Python -> html - lukeyd - Aug-01-2021

Hey

Sorry - im extremely new to this. Can you show me as an example so I know what you mean?


RE: Help with Python -> html - ndc85430 - Aug-01-2021

How are you learning Flask? The code in the index function is executed when a request to / is received right? Isn't that where you want to read the file and count its lines? Also, look at the documentation I linked to. Literally the first code example under "Rendering Templates" shows you how you pass a value for the variable in the template. The template is shown later on and uses a variable called name.


RE: Help with Python -> html - lukeyd - Aug-01-2021

Thank you, I managed to resolve it.

Appreciate your guidance!