Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flask dynamic data ?
#11
(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/...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,
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help on extract dynamic table data Dr_Strange 0 3,549 Apr-30-2021, 07:03 AM
Last Post: Dr_Strange
  Run function in parallel but inherite dynamic data from the previous function atizva 4 5,277 Jul-11-2018, 06:39 AM
Last Post: volcano63
  Method for pulling in dynamic table data brocq_18 1 4,365 Apr-03-2017, 04:07 PM
Last Post: snippsat

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.