Issue
I run thin code.
And I want that after 20 seconds that the variable msg will get the value "hello msg2".
And if I refresh the page I see there "hello msg2" instead of "msg1".
from flask import Flask, render_template
import time
mag = "msg1"
app = Flask(__name__)
@app.route("/")
def home():
return render_template("home.html")
@app.route("/index.html")
def user():
return render_template("index.html", msg=msg)
if __name__ == "__main__":
app.run(port=7654, debug=True)
The index.html
<!doctype html>
<html>
<head>
<title>Home page</title>
</head>
<body>
<h1>Home Page!5 {{ msg }} </h1>
</body>
</html>
It is possible? Because I could not run any more commands in Python while the site was running.
Solution
You can use threading
to spawn up a background thread to take care of updating value of msg
. Use time.sleep()
to add a delay to the execution.
from flask import Flask, render_template
import time
import threading
msg = "msg1"
# utility to change msg variable
def change_msg(delay=20):
time.sleep(delay)
global msg
msg = "msg2"
app = Flask(__name__)
@app.route("/")
def home():
return render_template("home.html")
@app.route("/index.html")
def user():
return render_template("index.html", msg=msg)
if __name__ == "__main__":
# spawn a thread that changes value of msg after a delay
t = threading.Thread(target=change_msg)
t.start()
app.run(port=7654, debug=True)
Answered By - ashwani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.