0
0
Flaskframework~5 mins

Why real-time matters in Flask

Choose your learning style9 modes available
Introduction

Real-time means your app updates instantly without waiting. It helps users see fresh info right away, making apps feel fast and alive.

Chat apps where messages appear immediately
Live sports scores updating as the game plays
Stock market apps showing price changes instantly
Collaborative tools where many people edit together
Notifications that pop up as soon as something happens
Syntax
Flask
from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('message')
def handle_message(msg):
    emit('message', msg, broadcast=True)

if __name__ == '__main__':
    socketio.run(app)

Flask alone handles normal web requests, but for real-time updates, Flask-SocketIO adds instant communication.

SocketIO uses WebSockets under the hood to keep a live connection open between client and server.

Examples
Sends a real-time message named 'update' with data to all connected clients.
Flask
socketio.emit('update', {'data': 'new info'})
Handles a user joining a chat room and sends a message only to that room.
Flask
@socketio.on('join')
def on_join(data):
    room = data['room']
    join_room(room)
    emit('status', {'msg': 'User joined room'}, room=room)
Sample Program

This simple Flask app uses Flask-SocketIO to send and receive messages instantly. The client sends a message after 1 second, and the server broadcasts a response that appears on the page immediately.

Flask
from flask import Flask
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/')
def index():
    return '''
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Real-time Demo</title>
      <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
      <script>
        document.addEventListener('DOMContentLoaded', () => {
          const socket = io();
          socket.on('message', msg => {
            const p = document.createElement('p');
            p.textContent = msg;
            document.body.appendChild(p);
          });
          setTimeout(() => {
            socket.emit('message', 'Hello from client!');
          }, 1000);
        });
      </script>
    </head>
    <body>
      <h1>Real-time message will appear below:</h1>
    </body>
    </html>
    '''

@socketio.on('message')
def handle_message(msg):
    emit('message', f'Server received: {msg}', broadcast=True)

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

Real-time apps need a way to keep connections open; Flask-SocketIO helps with that.

Test real-time features in a browser and watch messages appear without refreshing.

Real-time can improve user experience but may add complexity to your app.

Summary

Real-time means instant updates without page reloads.

Flask alone is not real-time; Flask-SocketIO adds this ability.

Use real-time for chat, live updates, and notifications.