Flask

Creating a Basic Chat Application with Flask


Introduction

Building a chat application is a common use case for Flask. In this guide, we'll create a basic chat application with Flask, covering key components such as the server, WebSocket communication, and a simple user interface. You can use this as a starting point and expand upon it for more advanced features.

Step 1: Setting Up Your Flask Application

Start by setting up your Flask application. Create a virtual environment and install Flask. Here's a sample directory structure:

my-chat-app/
    app.py
    templates/
        index.html
        chat.html
    static/
        script.js
        style.css
        

Step 2: Creating the Flask Server

Create a Flask server to handle incoming WebSocket connections. Use a library like Flask-SocketIO to simplify WebSocket communication. Here's a basic example of your Flask server:

# app.py
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/')
def index():
    return render_template('index.html')
@socketio.on('message')
def handle_message(message):
    socketio.emit('message', message)
if __name__ == '__main__':
    socketio.run(app, debug=True)
        

Step 3: Creating the User Interface

Design a simple user interface for your chat application. You can use HTML, CSS, and JavaScript for this. Here's a basic structure for your HTML templates:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Chat App</title>
    <link rel=`stylesheet` type=`text/css` href=`{{ url_for('static', filename='style.css') }}`>
</head>
<body>
    <div class=`container`>
        <h1>Welcome to the Chat App</h1>
        <form id=`username-form`>
            <input type=`text` id=`username` placeholder=`Enter your username` required>
            <button type=`submit`>Join</button>
        </form>
    </div>
    <script src=`{{ url_for('static', filename='script.js') }}`></script>
</body>
</html>
        

Create a separate chat.html template for the chat interface, and use JavaScript to handle WebSocket communication.

Step 4: JavaScript for WebSocket Communication

Implement WebSocket communication in your JavaScript code. Use a WebSocket library like Socket.io or Flask-SocketIO to manage real-time messaging. Here's a simplified example:

// script.js
const socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', () => {
    const username = prompt('Enter your username:');
    socket.emit('message', `${username} has joined the chat.`);
});
socket.on('message', (message) => {
    const messageDiv = document.createElement('div');
    messageDiv.innerHTML = message;
    document.getElementById('chat-messages').appendChild(messageDiv);
});
document.getElementById('chat-form').addEventListener('submit', (e) => {
    e.preventDefault();
    const messageInput = document.getElementById('message');
    socket.emit('message', messageInput.value);
    messageInput.value = '';
});
        

Step 5: Styling Your Chat App

Use CSS to style your chat application. Design a user-friendly interface with appropriate colors and layout. Here's a basic example:

/* style.css */
body {
    font-family: Arial, sans-serif;
}
.container {
    text-align: center;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    width: 300px;
}
button {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
}
#chat-messages {
    margin-top: 20px;
}
        

Step 6: Running Your Chat App

Run your Flask application with the following command:

python app.py
        

Access your chat application in a web browser and start chatting.

Conclusion

Creating a basic chat application with Flask is a great way to learn about real-time communication using WebSocket technology. This guide provides a simple foundation, but you can expand upon it by adding features like user authentication, multiple chat rooms, and message history storage. Have fun building and customizing your chat application!

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.