0
0
Flaskframework~30 mins

Polling as fallback in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Polling as fallback in Flask
📖 Scenario: You are building a simple Flask web app that shows the current server time updating every few seconds. Normally, you would use WebSockets for live updates, but as a fallback, you want to use polling to fetch the time repeatedly.
🎯 Goal: Create a Flask app with a route that returns the current server time as JSON. Then add a polling mechanism in the HTML page using JavaScript to fetch and display the time every 5 seconds.
📋 What You'll Learn
Create a Flask route /time that returns the current time in JSON format with key time
Create a basic HTML page served at / with a placeholder element to show the time
Add a JavaScript polling function that fetches /time every 5 seconds
Update the placeholder element with the fetched time on each poll
💡 Why This Matters
🌍 Real World
Polling is a simple fallback method to get live updates from a server when more advanced methods like WebSockets are not available or supported.
💼 Career
Understanding polling helps you build robust web apps that work reliably across different browsers and network conditions, a useful skill for frontend and backend developers.
Progress0 / 4 steps
1
Set up Flask app and time route
Create a Flask app instance called app. Then create a route @app.route('/time') that returns a JSON response with the current server time under the key 'time'. Use datetime.now().strftime('%H:%M:%S') to format the time string.
Flask
Need a hint?

Import Flask and jsonify from flask, and datetime from datetime. Create the app and define the route returning JSON with the current time.

2
Add HTML page with time display placeholder
Add a route @app.route('/') that returns a simple HTML page as a string. The page should have a <div> with id='time-display' where the time will be shown. Include a <script> tag placeholder for JavaScript below the div.
Flask
Need a hint?

Define the / route returning HTML with a div having id='time-display' and an empty script tag below it.

3
Add JavaScript polling function
Inside the <script> tag in the HTML returned by index(), add a JavaScript function called pollTime() that uses fetch('/time') to get the JSON time, then updates the innerText of the element with id='time-display'. Use setInterval to call pollTime() every 5000 milliseconds (5 seconds). Also call pollTime() once immediately to show time on page load.
Flask
Need a hint?

Write a JavaScript function pollTime() that fetches /time, parses JSON, updates the div text, calls it once, and sets interval every 5 seconds.

4
Run the Flask app with debug mode
Add the standard Flask app runner code at the bottom: if __name__ == '__main__': then app.run(debug=true) to start the server in debug mode.
Flask
Need a hint?

Add the standard Flask app runner block to start the server with debug mode enabled.