Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with Python -> html
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 I have the following code;

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

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 ?
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.

So the full is this;

from flask import Flask, render_template, request

app = Flask(__name__)

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


if __name__ == "__main__":
The full index.html is this;

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

I hope this makes sense ?
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).

Sorry - im extremely new to this. Can you show me as an example so I know what you mean?
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.
Thank you, I managed to resolve it.

Appreciate your guidance!
ndc85430 likes this post

Possibly Related Threads…
Thread Author Replies Views Last Post
  reading html and edit chekcbox to html jacklee26 5 1,887 Jul-01-2021, 10:31 AM
Last Post: snippsat
  HTML to Python to Windows .bat and back to HTML perfectservice33 0 1,406 Aug-22-2019, 06:31 AM
Last Post: perfectservice33

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020