0
0
Flaskframework~5 mins

Server-Sent Events alternative in Flask

Choose your learning style9 modes available
Introduction

Server-Sent Events (SSE) let a server send updates to a web page automatically. Sometimes, you need another way to do this, like using WebSockets, which allow two-way communication between the server and the browser.

You want real-time chat where users can send and receive messages instantly.
You need to update a dashboard with live data from the server.
You want to build a game where the server and client talk back and forth quickly.
You want to push notifications to users without them refreshing the page.
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('response', msg, broadcast=True)

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

This example uses Flask-SocketIO, a popular Flask extension for WebSockets.

WebSockets allow two-way communication, unlike SSE which is one-way from server to client.

Examples
This listens for a client connecting to the server.
Flask
from flask_socketio import SocketIO

socketio = SocketIO(app)

@socketio.on('connect')
def on_connect():
    print('Client connected')
This sends a chat message to all connected clients.
Flask
@socketio.on('chat message')
def handle_chat(msg):
    emit('chat response', msg, broadcast=True)
Sample Program

This is a simple chat app using Flask and WebSockets. When you type a message and click send, it goes to the server and then broadcasts to all connected clients, updating their message list instantly.

Flask
from flask import Flask, render_template_string
from flask_socketio import SocketIO, emit

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

html = '''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Chat</title>
  <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
</head>
<body>
  <h1>Simple WebSocket Chat</h1>
  <input id="msgInput" autocomplete="off" placeholder="Type message..." />
  <button onclick="sendMessage()">Send</button>
  <ul id="messages"></ul>

  <script>
    const socket = io();
    const messages = document.getElementById('messages');

    socket.on('chat response', function(msg) {
      const li = document.createElement('li');
      li.textContent = msg;
      messages.appendChild(li);
    });

    function sendMessage() {
      const input = document.getElementById('msgInput');
      if(input.value.trim() !== '') {
        socket.emit('chat message', input.value);
        input.value = '';
      }
    }
  </script>
</body>
</html>
'''

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

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

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

WebSockets require a client library like Socket.IO to work smoothly with Flask.

Unlike SSE, WebSockets allow the client to send messages to the server too.

Make sure to run the Flask app with SocketIO's run method, not the usual app.run().

Summary

Server-Sent Events send updates one-way from server to browser.

WebSockets are a good alternative for two-way real-time communication.

Flask-SocketIO makes it easy to add WebSockets to your Flask app.