Implementing Real-Time Notifications with Flask and WebSockets

 o implement real-time notifications in a Flask application using WebSockets, you can use Flask-SocketIO, which provides easy integration with Flask for WebSocket support.

Here's how you can implement it:

Step 1: Install the necessary packages

First, you need to install Flask and Flask-SocketIO. You can do this using pip:

bash
pip install Flask Flask-SocketIO

Step 2: Set up the Flask application with WebSocket support

Create a Python file, e.g., app.py, and configure the Flask application with Flask-SocketIO.

python
from flask import Flask, render_template from flask_socketio import SocketIO, send, emit app = Flask(__name__) socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') # Event for real-time notification @socketio.on('send_message') def handle_message(message): print('Received message: ' + message) # Sending the message to all connected clients emit('receive_message', message, broadcast=True) if __name__ == '__main__': socketio.run(app, debug=True)

Step 3: Create the HTML page to interact with WebSockets

Create an index.html file in the templates folder. This will serve as the frontend interface to interact with the Flask WebSocket.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real-Time Notifications</title> <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script> <script> // Connect to the WebSocket server var socket = io.connect('http://' + document.domain + ':' + location.port); // Send message to server function sendMessage() { var message = document.getElementById('message').value; socket.emit('send_message', message); } // Receive messages from the server socket.on('receive_message', function(message) { var notification = document.createElement('p'); notification.innerText = message; document.getElementById('notifications').appendChild(notification); }); </script> </head> <body> <h1>Real-Time Notifications</h1> <input type="text" id="message" placeholder="Type a message"> <button onclick="sendMessage()">Send</button> <div id="notifications"> <!-- New notifications will appear here --> </div> </body> </html>

Step 4: Run the Flask application

To start the Flask application, run the following command in the terminal:

bash
python app.py

Step 5: Test the real-time notifications

  1. Open a web browser and navigate to http://localhost:5000.

  2. Open multiple tabs or windows of the same page.

  3. In one of the tabs, type a message and click "Send."

  4. The message will be broadcasted to all connected clients in real time.

How it works:

  • SocketIO enables bi-directional communication between the server and clients.

  • The @socketio.on('send_message') event listener listens for messages from clients.

  • When a message is received, it's broadcasted to all connected clients with emit('receive_message', message, broadcast=True).

  • The frontend JavaScript listens for the 'receive_message' event and updates the page with new notifications.

Additional Features:

You can expand this basic example to include:

  • User-specific notifications by emitting messages only to specific clients using emit('receive_message', message, room=user_id).

  • Notification persistence by saving notifications to a database and displaying them when users reconnect.

  • Advanced UI features such as message sound alerts, read/unread indicators, etc.

Comments

Popular posts from this blog

How to Repurpose Old Content for Better Engagement

Introduction to AWS for Data Science Beginners

Why Learn Full Stack Java?