Python Forum
Flask dynamic data ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Flask dynamic data ? (/thread-35536.html)

Pages: 1 2


Flask dynamic data ? - korenron - Nov-14-2021

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,


RE: Flask dynamic data ? - ndc85430 - Nov-14-2021

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.


RE: Flask dynamic data ? - buran - Nov-14-2021

One way is to use AJAX with jQuery to dynamically update the content on client side


RE: Flask dynamic data ? - ndc85430 - Nov-14-2021

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.


RE: Flask dynamic data ? - buran - Nov-14-2021

(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.


RE: Flask dynamic data ? - snippsat - Nov-14-2021

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.


RE: Flask dynamic data ? - jamesaarr - Nov-15-2021

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.


RE: Flask dynamic data ? - DeaD_EyE - Nov-15-2021

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


RE: Flask dynamic data ? - buran - Nov-15-2021

(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.


RE: Flask dynamic data ? - jamesaarr - Nov-15-2021

(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