Creating a Real-Time Notification System with Python and WebSocket

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up the Project
  4. Creating the WebSocket Server
  5. Creating the WebSocket Client
  6. Testing the Real-Time Notification System
  7. Conclusion

Introduction

In this tutorial, we will learn how to create a real-time notification system using Python and the WebSocket protocol. The WebSocket protocol allows for bidirectional communication between client and server over a single, long-lived connection, making it ideal for implementing real-time applications.

By the end of this tutorial, you will have a working real-time notification system where the server can push notifications to all connected clients instantly.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming language and web development concepts. You should also have the following software installed:

  • Python 3
  • Flask web framework
  • Flask-SocketIO library
  • JavaScript (for the client-side implementation)

Setting Up the Project

  1. First, create a new directory for your project. Open a terminal or command prompt, navigate to the desired location, and run the following command:

     mkdir real-time-notification-system
    
  2. Change to the project directory:

     cd real-time-notification-system
    
  3. Create a virtual environment to isolate the project dependencies:

     python3 -m venv venv
    
  4. Activate the virtual environment:

    • For Windows:

        venv\Scripts\activate
      
    • For macOS/Linux:

        source venv/bin/activate
      
  5. Install the necessary Python packages:

     pip install flask flask-socketio
    
  6. Create a new Python file called app.py to start building our notification system:

     touch app.py
    

    Creating the WebSocket Server

We will begin by creating the server-side of our real-time notification system. Open the app.py file in your preferred text editor and let’s get started.

  1. Import the necessary modules:

     from flask import Flask
     from flask_socketio import SocketIO, emit
    
  2. Initialize the Flask application and the SocketIO extension:

     app = Flask(__name__)
     app.config['SECRET_KEY'] = 'secret'
     socketio = SocketIO(app)
    
  3. Create a route and a function to handle the client connection:

     @app.route('/')
     def index():
         return 'WebSocket Server'
    
     @socketio.on('connect')
     def handle_connect():
         emit('notification', 'Connected')
    
  4. Add the following code to start the server:

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

    Congratulations! You have created the WebSocket server for our real-time notification system. Save the app.py file and move on to the next section.

Creating the WebSocket Client

Now, let’s create the client-side implementation for our real-time notification system using JavaScript.

  1. In the project directory, create a new folder called static. Inside the static folder, create a new JavaScript file called client.js:

     mkdir static
     touch static/client.js
    
  2. Open the client.js file and add the following code:

     const socket = io();
    
     socket.on('notification', (message) => {
         console.log(`Notification: ${message}`);
     });
    
  3. Next, create an HTML file called index.html in the project directory and add the following code:

     <!DOCTYPE html>
     <html>
     <head>
         <title>Real-Time Notification System</title>
     </head>
     <body>
         <h1>Real-Time Notification System</h1>
    
         <script src="/socket.io/socket.io.js"></script>
         <script src="static/client.js"></script>
     </body>
     </html>
    

    Congratulations! You have created the client-side implementation for our real-time notification system. Save the index.html and client.js files.

Testing the Real-Time Notification System

  1. Start the WebSocket server by running the following command in the terminal:

     python app.py
    
  2. Open your web browser and navigate to http://localhost:5000. You should see the “Real-Time Notification System” heading.

  3. Open the browser’s developer console. You should see a notification stating that you are connected to the WebSocket server.

  4. Open a new terminal window and run the following command to send a test notification to connected clients:

     curl -X POST http://localhost:5000 -d 'test notification'
    
  5. Check the browser’s developer console. You should see a new notification message logged.

Congratulations! You have successfully created a real-time notification system using Python and WebSocket.

Conclusion

In this tutorial, we learned how to create a real-time notification system using Python and WebSocket. We started by setting up the project and installing the necessary dependencies. Then, we created the WebSocket server using Flask and Flask-SocketIO. Finally, we implemented the client-side using JavaScript.

By now, you should have a good understanding of how to build a real-time notification system and adapt it to your own projects. You can further enhance this system by adding user authentication, storing notifications in a database, and customizing the client-side interface.

Feel free to experiment with different approaches and add additional features to make the system more robust and versatile. Happy coding!