Welcome to this comprehensive guide on broadcasting messages using Flask! By the end of this tutorial, you'll have a solid understanding of how to use Flask's built-in Flask-SocketIO extension for real-time communication. Let's dive in! 🎯
Before we begin, ensure you have Flask installed. If not, install it using:
pip install flask flask-socketioNow, create a new Python file app.py and let's get started!
Before we add SocketIO, let's create a simple Flask application.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)Create a templates folder with a home.html file containing:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Tutorial - Broadcasting Messages</title>
</head>
<body>
<h1>Welcome to Flask Tutorial!</h1>
</body>
</html>Now, let's integrate Flask-SocketIO for real-time communication.
pip install flask-socketioUpdate the app.py file:
from flask import Flask, render_template
from flask_socketio import SocketIO, join_room, leave_room, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def home():
return render_template('home.html')
@socketio.on('join')
def on_join(data):
print(f"User joined room: {data['room']}")
join_room(data['room'])
@socketio.on('leave')
def on_leave():
print("User left room")
leave_room()
@socketio.on('message')
def handle_message(msg):
print(f"Message received: {msg}")
send(msg, to=msg['room'])
if __name__ == '__main__':
socketio.run(app, debug=True)Update the home.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Tutorial - Broadcasting Messages</title>
<script src="//cdn.socket.io/socket.io-3.1.1.min.js"></script>
<script>
const socket = io();
socket.on('connect', () => {
console.log('Connected to server');
const room = prompt('Enter a room to join');
socket.emit('join', { room });
});
socket.on('message', data => {
console.log(data);
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
socket.emit('leave');
});
function sendMessage(message) {
socket.emit('message', { room: localStorage.getItem('room'), text: message });
}
</script>
</head>
<body>
<h1>Welcome to Flask Tutorial!</h1>
<input type="text" id="message" placeholder="Type your message here" />
<button onclick="sendMessage(document.getElementById('message').value)">Send</button>
</body>
</html>Now, when you run the application, you should be able to join a room and send messages! 🎉
SECRET_KEY is used to sign cookies and is essential for secure sessions.socket.io library is not included in our project, so we have to include it from a CDN in our HTML.room variable in the local storage, so they persist across page reloads.What is the purpose of the `SECRET_KEY` in our Flask app?
Stay tuned for more advanced examples on broadcasting messages in Flask! 🎯