Flask Tutorials: Broadcasting Messages 📣

beginner
23 min

Flask Tutorials: Broadcasting Messages 📣

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! 🎯

Getting Started 📝

Before we begin, ensure you have Flask installed. If not, install it using:

bash
pip install flask flask-socketio

Now, create a new Python file app.py and let's get started!

Creating a Basic Flask App 💡

Before we add SocketIO, let's create a simple Flask application.

python
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:

html
<!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>

Introducing Flask-SocketIO 🚀

Now, let's integrate Flask-SocketIO for real-time communication.

bash
pip install flask-socketio

Update the app.py file:

python
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:

html
<!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! 🎉

📝 Note:

  • The SECRET_KEY is used to sign cookies and is essential for secure sessions.
  • The socket.io library is not included in our project, so we have to include it from a CDN in our HTML.
  • Messages are stored in the room variable in the local storage, so they persist across page reloads.

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `SECRET_KEY` in our Flask app?

Stay tuned for more advanced examples on broadcasting messages in Flask! 🎯