Build Your Own Chat Application with Python: A Step-by-Step Guide

Creating a chat application with Python is a great way to learn more about the language, enhance your skills, and develop a useful tool. In this tutorial, we'll walk you through building a basic chat app using Python, Flask, and WebSocket.

Table of Contents

  1. Prerequisites
  2. Setting Up the Project
  3. Creating the Flask App
  4. Integrating WebSocket
  5. Building the Frontend
  6. Running the Chat Application
  7. Conclusion

Prerequisites

To follow this tutorial, you'll need:

  • Python 3.6 or higher
  • Basic knowledge of Python, HTML, CSS, and JavaScript
  • A text editor or IDE, such as Visual Studio Code
  • pip, the Python package installer

Setting Up the Project

  1. Create a new directory for your project:

    mkdir python-chat-app
    cd python-chat-app
  2. Set up a virtual environment:

    python -m venv venv
  3. Activate the virtual environment:

    • On macOS and Linux:

      source venv/bin/activate
    • On Windows:

      .\venv\Scripts\activate
  4. Install Flask and Flask-SocketIO:

    pip install Flask Flask-SocketIO

Creating the Flask App

  1. In your project directory, create a new file called app.py.

  2. Import the necessary libraries and initialize the Flask app and SocketIO:

    from flask import Flask, render_template
    from flask_socketio import SocketIO
    
    app = Flask(__name__)
    socketio = SocketIO(app)
    
  3. Create a route for the main page:

    @app.route('/')
    def index():
        return render_template('index.html')
    
  4. Add the if __name__ == '__main__': block to run the app:

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

Integrating WebSocket

  1. In app.py, import the send and join_room functions from Flask-SocketIO:

    from flask_socketio import send, join_room
    
  2. Create an event handler for new messages:

    @socketio.on('message')
    def handle_message(data):
        send(data, broadcast=True)
    

Building the Frontend

  1. In your project directory, create a new folder called templates.

  2. Inside templates, create a new file called index.html.

  3. Add the following code to index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Python Chat App</title>
    </head>
    <body>
        <h1>Chat Room</h1>
        <div id="messages"></div>
        <form id="messageForm">
            <input type="text" id="message" placeholder="Type your message here" autofocus>
            <button type="submit">Send</button>
        </form>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script>
        <script>
            const socket = io.connect();
    
            document.getElementById('messageForm').addEventListener('submit', (event) => {
                event.preventDefault();
                const message = document.getElementById('message').value;
                socket.emit('message', message);
                document.getElementById('message').value = '';
            });
    
            socket.on('message', (data) => {
                const messages = document.getElementById('messages');
                messages.innerHTML += `<p>${data}</p>`;
            });
        </script>
    </body>
    </html>
    

Running the Chat Application

  1. In your terminal, navigate to the project directory and run the following command:

    python app.py
  2. Open a web browser and visit http://127.0.0.1:5000.

  3. Start chatting! Open multiple browser windows or tabs to test the chat functionality.

Conclusion

Congratulations! You've built a simple chat application using Python, Flask, and WebSocket. You can now explore more advanced features, such as adding user authentication, creating private chat rooms, and adding emojis. Happy coding!

An AI coworker, not just a copilot

View VelocityAI