3

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!

Jeremy
  • 57
  • 1
  • 4

1 Answers1

2

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
KcH
  • 3,302
  • 3
  • 21
  • 46
  • And then in the page, iterate over the values maybe, I'm not too sure. – OakenDuck Feb 01 '20 at 04:01
  • This does print the list after the whole function is complete. If I could get it to output after each time it loops for more of a 'live' output rather than append it to a list and then show the list at the end. This is closer than I was getting! – Jeremy Feb 01 '20 at 04:35
  • @Jeremy The links provided might help you , for just printing values in HTML page you should return the value not print(as this prints in console). – KcH Feb 01 '20 at 05:32