Flask is a micro web framework written in Python. It provides a simple and lightweight way to build web applications. Flask follows the Model - View - Controller (MVC) architectural pattern, where the application logic is separated into different components. In a Flask application, you can define routes to handle different HTTP requests and render templates to display HTML pages.
WebSocket is a communication protocol that provides full - duplex communication channels over a single TCP connection. Unlike traditional HTTP, which is a request - response protocol, WebSocket allows continuous communication between the client and the server. In a chat application, WebSocket is used to enable real - time messaging, where messages can be sent and received instantly without the need for repeated HTTP requests.
These are the fundamental technologies for building the user interface of a web application. HTML is used to structure the content of the page, CSS is used to style the page, and JavaScript is used to add interactivity. In the context of a chat app, JavaScript is used to handle WebSocket connections and update the chat window in real - time.
First, create a new directory for your project and navigate to it in the terminal. Then, create a virtual environment and activate it:
mkdir flask_chat_app
cd flask_chat_app
python3 -m venv venv
source venv/bin/activate
Next, install the necessary packages: Flask and Flask - SocketIO. SocketIO is a library that simplifies WebSocket communication in Flask.
pip install flask flask-socketio
Create a new Python file, for example, app.py
, and add the following code:
from flask import Flask, render_template
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('message')
def handle_message(message):
send(message, broadcast=True)
if __name__ == '__main__':
socketio.run(app, debug=True)
In this code:
index
route renders an HTML template named index.html
.handle_message
function is a SocketIO event handler. When a message
event is received, it broadcasts the message to all connected clients.Create a templates
directory in your project root and inside it, create an index.html
file with the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Chat App</title>
<style>
/* Simple CSS styling for the chat window */
#chat-window {
border: 1px solid #ccc;
height: 300px;
overflow-y: scroll;
padding: 10px;
}
#message-input {
width: 80%;
}
</style>
</head>
<body>
<div id="chat-window"></div>
<input type="text" id="message-input" placeholder="Type your message">
<button id="send-button">Send</button>
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js"></script>
<script>
const socket = io();
const chatWindow = document.getElementById('chat-window');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
sendButton.addEventListener('click', () => {
const message = messageInput.value;
if (message) {
socket.emit('message', message);
messageInput.value = '';
}
});
socket.on('message', (message) => {
const newMessage = document.createElement('p');
newMessage.textContent = message;
chatWindow.appendChild(newMessage);
});
</script>
</body>
</html>
In this HTML file:
io()
.message
event to the server with the typed message.message
event is received from the server, we create a new paragraph element and append it to the chat window.You can further enhance the user interface by adding more CSS styles. For example, you can style the chat messages differently based on whether they are sent by the user or received from others. You can also add features like message timestamps and user avatars.
/* Add more CSS styles for better appearance */
#chat-window p {
margin: 5px 0;
padding: 5px;
border-radius: 5px;
}
#chat-window p:nth-child(odd) {
background-color: #f0f0f0;
}
Building a chat app with Flask is a great way to learn about web development, real - time communication, and user interface design. By understanding the core concepts, typical usage scenarios, and following best practices, you can create a functional and secure chat app. Remember to be aware of common pitfalls and continuously improve your application based on user feedback.