(Nov-15-2021, 12:59 PM)DeaD_EyE Wrote: In one of my projects, I have a status display for a rechargeable battery. To get the current values, I've written a small JavaScript, which fetches the information from a route and assigning the information to the fields. I use the id
to address the Elements.
The modified template with JavaScript:
<!DOCTYPE html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, World!</h1>
<h2>The date and time on the server is</h2>
<h2 id="time">{{ time }}</p></h2>
</body>
<script type="text/javascript">
function update() {
let doc = document.getElementById("time");
fetch("/api/time").then(
response => response.json()
).then(
function(data) {
console.log(data["now"]);
doc.innerText = data["now"];
});
}
// update all 10000 ms
(function () {
update();
setInterval(function () {
update();
}, 1000);
})();
</script>
</html>
And the minimalistic small flask example:
import datetime
from flask import Flask, render_template
app = Flask(__name__, template_folder=".")
# template_folder was for testing
# I put the index.html next to the program, so the template
# is in my case not in templates
@app.route("/")
def root():
return render_template("index.html", time=datetime.datetime.now().isoformat(), title="TEST")
@app.route("/api/time")
def now():
return {"now": datetime.datetime.now().isoformat()}
app.run()
This is not the best solution because you've to write a small amount of JavaScript.
Better approach is HTMX for example. Here is a link to a well known podcast: https://talkpython.fm/episodes/show/321/htmx-clean-dynamic-html-pages