Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - Print to HTML not console [duplicate]

Tags:

python

html

flask

I have a simple example of my problem, I cannot get a python script/function result to be sent to Flask HTML when the script is being ran. I have tried everything I saw here on SO, I'm sure it's possible, but I have been stuck for a while. Here is just a simple example of what I cannot get working.

Flask Code:

from flask import Flask, render_template
import time
app = Flask(__name__)

def mycounter():
    for x in range(0, 10):
        print(f"<p> {x} </p>")
        time.sleep(1)

@app.route("/")
@app.route("/index")
def index():
    return render_template('index.html', output=mycounter())

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

HTML Code:

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <p>{{ output }}</p>
</body>
</html>

All I want this to do is count from 0 to 9 every second and print to HTML every second rather than the console. I have tried popen but perhaps I am using it wrong? Thank You!

like image 365
Jeremy Avatar asked Mar 02 '26 10:03

Jeremy


1 Answers

Instead of printing you should return values I guess:

def mycounter():
    test=[]
    for x in range(0, 10):
        time.sleep(1)
        test.append(x)
    return test
like image 135
Codenewbie Avatar answered Mar 03 '26 22:03

Codenewbie