Create a live chat application with Redis pub/sub and Flask

Posted by

Building a Real Time Chat Application with Redis Pub/Sub and Flask

Building a Real Time Chat Application with Redis Pub/Sub and Flask

Real time chat applications are becoming increasingly popular as people look for ways to communicate instantly with others. In this article, we will explore how to build a real time chat application using Redis Pub/Sub and Flask.

What is Redis Pub/Sub?

Redis Pub/Sub (Publish/Subscribe) is a messaging system that allows different parts of an application to communicate with each other through channels. When a message is published to a channel, all subscribers to that channel will receive the message in real time.

Setting up Redis and Flask

To get started, you will need to have Redis installed on your machine. You can download and install Redis from the official website. Once Redis is installed, you will also need to install the Redis Python library with pip.

pip install redis

Next, you will need to create a Flask application. Make sure you have Flask installed on your machine.

pip install Flask

Building the Chat Application

Now that you have Redis and Flask set up, you can start building the chat application. First, create a new Python file and import the necessary libraries.

import redis
from flask import Flask, render_template, request

Next, create a connection to the Redis server and set up the Flask application.

app = Flask(__name__)
redis_client = redis.Redis()

Now, you can create the routes for the chat application. You will need routes for sending messages, subscribing to messages, and rendering the chat interface.

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

@app.route('/send_message', methods=['POST'])
def send_message():
    message = request.form.get('message')
    redis_client.publish('chat_channel', message)
    return 'Message Sent'

@app.route('/stream')
def stream():
    pubsub = redis_client.pubsub()
    pubsub.subscribe('chat_channel')
    
    for message in pubsub.listen():
        if message['type'] == 'message':
            yield 'data: ' + message['data'] + 'nn'

Creating the Chat Interface

Finally, you will need to create the chat interface using HTML, CSS, and JavaScript. You can use a simple HTML form to send messages and an EventSource object in JavaScript to listen for messages from the Redis server.

<!DOCTYPE html>
<html>
<head>
    <title>Real Time Chat</title>
    <script type="text/javascript">
        const chatDisplay = document.getElementById('chatDisplay');
        const source = new EventSource('/stream');
        
        source.onmessage = function(event) {
            chatDisplay.innerHTML += event.data + '<br/>';
        }
        
        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            fetch('/send_message', {
                method: 'POST',
                body: new URLSearchParams({message: messageInput.value}),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });
            messageInput.value = '';
        }
    </script>
</head>
<body>
    <div id="chatDisplay"></div>
    <input type="text" id="messageInput" />
    <button onclick="sendMessage()">Send</button>
</body>
</html>

Conclusion

By following these steps, you can build a real time chat application using Redis Pub/Sub and Flask. This type of application is perfect for situations where users need to communicate instantly and see messages in real time. Feel free to customize the application further and add features like user authentication and message history.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@rakeshchauraiya9782
5 months ago

मेरा सपना सच हुआ

@shraddhatiwari397
5 months ago

Informative and helpful, step wise coding is really great👍

@AshishPandey-yd8jd
5 months ago

Superb❤❤