Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flask dynamic data ?
#1
Hello,
I want to build a html page that show me dynamic data - at first just the time
this is what I have done:
this is the index.html

<!DOCTYPE html>
   <head>
      <title>{{ title }}</title>
   </head>
   <body>
      <h1>Hello, World!</h1>
      <h2>The date and time on the server is: {{ time }}</h2>
   </body>
</html>
this is the flask code
from flask import Flask, render_template
import datetime
app = Flask(__name__)

@app.route("/")
def hello():
    now = datetime.datetime.now()
    timeString = now.strftime("%d-%m-%Y %H:%M:%S")
    templateData = {
        'title' : 'HELLO!',
        'time': timeString,     
         }
    return render_template('index.html', **templateData)

if __name__ == "__main__":
   app.run(host='0.0.0.0', port=8090, debug=True)
how do I make it update the time once every x sec ?
without doing anything on the browser ...

Thanks,
Reply
#2
HTTP is request/response, meaning that the client had to make the request for the data. If you want the server to push data to the client, then at least one way to do that is using WebSocket. Flask may have an extension for WebSocket; I'm not sure. Either way, you still need to make changes client-side.
Reply
#3
One way is to use AJAX with jQuery to dynamically update the content on client side
ndc85430 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Do note with AJAX, though, it's the client pulling the data, rather than the server pushing it. Both work, depends where you want to control things.
buran likes this post
Reply
#5
(Nov-14-2021, 04:49 PM)ndc85430 Wrote: it's the client pulling the data
Yeah, that's why I edited my answer - from "another way" to "one way". Technically it's what you already mentioned - client-side making a request, but not refresh the whole page.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Did you look at some of the links in my last post?
In this link using AJAX(no reload of Brower) and update random value every 10-sec.
Someone has tested code on Raspberry Pi.
YogiMike Wrote:Thanks for the post snippsat. I used your example (with data changes) to use flask on my Raspberry Pi 2 with a Sense Hat to have a dynamic webpage which automatically updates Humidity, Temp, Barometric Pressure, and other data. It worked marvelously!!

Here a link with Advanced Python Scheduler,no AJAX,but a trick for updating web-page.
window.onload = timedRefresh(15000); 
This can be useful if don't need update all the time.

Quote:Flask may have an extension for WebSocket; I'm not sure. Either way, you still need to make changes client-side.
The most used way for this in this in Flask is to use Flask-SocketIO and  socket.io on the client side.
Reply
#7
Hi all,

Another way you can do this is in Flask itself. If you set it up so your Flask program says something like:

from flask import Flask
#import your date/time module however you like,my choice module is below and my example uses this.
from datetime import date
app = Flask(__name__)
@app.route('/')
def home():
    date = date.today()
    return '''<html><body><h1>Todays date is {date}</h1></body></html>'''
The above code won't work exactly for you, it's just to give you an idea, but with this, you shouldn't need a seperate HTML file. Your flask site will just update as it is refreshed in the client's browser.

Edit: You can entirely use the render template method, don't feel I'm correcting you, just offering an alternative method.
while dad_has_cigs == True:
    happiness = True
    if dad_has_cigs == False:
    print("Dad come home!")
    happiness = not happiness
    break
Reply
#8
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#9
(Nov-15-2021, 09:47 AM)jamesaarr Wrote: Your flask site will just update as it is refreshed in the client's browser.
That's exactly what OP is trying to avoid - the need to manually refresh the browser. Their code is doing what you suggest with html code is static file/template.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
(Nov-15-2021, 01:19 PM)buran Wrote:
(Nov-15-2021, 09:47 AM)jamesaarr Wrote: Your flask site will just update as it is refreshed in the client's browser.
That's exactly what OP is trying to avoid - the need to manually refresh the browser. Their code is doing what you suggest with html code is static file/template.

Ah sorry, misunderstood!

I'm aware their code does the same thing, was just offering an alternative! :)

Thanks
while dad_has_cigs == True:
    happiness = True
    if dad_has_cigs == False:
    print("Dad come home!")
    happiness = not happiness
    break
Reply


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

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020