0
0
Flaskframework~5 mins

Polling as fallback in Flask

Choose your learning style9 modes available
Introduction

Polling as fallback helps your web app check for updates regularly when real-time methods don't work. It keeps the app updated by asking the server often.

When WebSockets or Server-Sent Events are not supported by the browser.
When network conditions block real-time connections.
When you want a simple way to update data without complex setup.
When you need a backup method to keep data fresh if real-time fails.
Syntax
Flask
import time
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/poll')
def poll():
    # Return latest data or status
    data = {'message': 'Hello from server', 'time': time.time()}
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True)

The server provides an endpoint that the client calls repeatedly.

The client uses JavaScript to request this endpoint at intervals.

Examples
Simple polling endpoint returning current time and status.
Flask
import time
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/poll')
def poll():
    return jsonify({'status': 'ok', 'time': time.time()})
Polling endpoint that tells client if new data is available based on last check time.
Flask
import time
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/poll')
def poll():
    last_check = float(request.args.get('last_check', 0))
    current_time = time.time()
    if current_time - last_check > 5:
        return jsonify({'update': True, 'time': current_time})
    else:
        return jsonify({'update': False})
Sample Program

This Flask app creates a /poll endpoint that returns a message and the current server time. A client can call this endpoint repeatedly to get updates.

Flask
import time
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/poll')
def poll():
    data = {'message': 'Hello from server', 'time': time.strftime('%H:%M:%S')}
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Polling can cause more server load because it sends many requests.

Choose a reasonable interval (like every 5 seconds) to avoid overload.

Use polling as a fallback only when real-time methods are not possible.

Summary

Polling asks the server for updates regularly by sending repeated requests.

It is simple but less efficient than real-time communication.

Use polling as a backup when other methods fail or are unsupported.