Nov-17-2021, 07:37 AM
(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 theid
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/...html-pages
will this also refresh the page?
or it will just refresh the data ?
because this look like a much better\clean solution
Thanks,