Camille BOUQUET
Camille BOUQUET

Reputation: 423

Timer in python and html with Flask

I would like to display a timer in my html page. I am using Flask python. I would like to display the animation when you see the seconds are decreasing. I tried the following code without a big success. When I try only the python function, it's working on my terminal but when I want to display it on my HTML page, it's not working anymore and I have the following issue: The browser (or proxy) sent a request that this server could not understand.

Here is my code:

file.py:

from flask import Flask, flash, redirect, render_template, request, session, abort
import time 

app = Flask(__name__)

@app.route("/")
def index():
    value = "bonjour"
    title_html = value
    # function call
    t = request.form['time']
    countdown(int(t))
    return render_template(
    'display.html',message=title_html, time=t)
    

# define the countdown func.
def countdown(t):
    
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1  
        return t
  
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

and my html display.html:

<!DOCTYPE HTML>
<html>
<head>
    <link rel="stylesheet" href='/static/main.css'/>
    <!-- <script type=text/javascript src="{{
        url_for('static', filename='js/main.js') }}"></script> -->
    <title>Rotation of the motor</title>
</head>
<body>
    <h1>Hello! Here are some information about your dish:</h1>

    <p>{{message}}</p>
    <p><input type='text' value="{{time}}" name="time">{{time}}</p>
</body>
</html>

Upvotes: 0

Views: 1038

Answers (1)

imxitiz
imxitiz

Reputation: 3987

If you want your code to work like this then you have to send requests multiple times. Because if you sent request to server one time then it will stay there for t second and then send response at last. But alternatively you can use javascript in client side which is the best idea, for this kind of things.

Upvotes: 1

Related Questions