Flask-SocketIO Basics 🎯

beginner
12 min

Flask-SocketIO Basics 🎯

Welcome to our comprehensive guide on Flask-SocketIO! In this tutorial, we'll explore how to use Socket.IO with Flask, a popular Python web framework, to create real-time, interactive web applications. Let's dive in! 🐰

Introduction to Flask and Socket.IO 📝

Flask

Flask is a lightweight Python web framework that provides an easy-to-use interface for building web applications. It's perfect for beginners and small projects due to its simplicity and ease of use.

Socket.IO

Socket.IO is a JavaScript library that enables real-time, bidirectional communication between web clients and servers. It works by using WebSockets when available, or falling back to other transports like HTTP polling for compatibility with older browsers.

Combining Flask and Socket.IO 🚀

By integrating Socket.IO with Flask, we can create dynamic, interactive web applications that respond to user actions in real-time. Let's get started!

Setting Up a Flask-SocketIO Project 💡

Before we begin, ensure you have Python and Flask installed on your system. To install Flask-SocketIO, use the following command:

bash
pip install Flask-SocketIO

Now, create a new directory for your project and navigate to it in the terminal:

bash
mkdir flask-socketio-tutorial cd flask-socketio-tutorial

Next, create a new file called app.py and open it in your favorite text editor:

bash
touch app.py nano app.py

Creating a Basic Flask Application 📝

Let's start by building a simple Flask application without Socket.IO. This will serve as the foundation for our real-time app.

python
# app.py from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hello, World!" if __name__ == '__main__': app.run(debug=True)

Run the application using the following command:

bash
python app.py

Open your web browser and navigate to http://127.0.0.1:5000 to see the output.

Integrating Socket.IO with Flask 💡

Now, let's add Socket.IO to our Flask application. Update app.py to include SocketIO and initialize it in the __init__.py file:

python
# app.py from flask import Flask, render_template from flask_socketio import SocketIO, join_room, leave_room, emit app = Flask(__name__) socketio = SocketIO(app) @app.route('/') def home(): return render_template('home.html') if __name__ == '__main__': app.run(debug=True) # __init__.py from flask import Flask from flask_socketio import SocketIO, join_room, leave_room, emit socketio = SocketIO()

Create a new folder called templates and add a file called home.html inside it:

bash
mkdir templates touch templates/home.html

Open home.html in your text editor and add some basic HTML structure:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flask SocketIO Tutorial</title> <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script> <script src="{{ url_for('socket.js') }}"></script> </head> <body> <h1>Flask SocketIO Tutorial</h1> <p id="messages"></p> <form id="message-form"> <input type="text" id="message" placeholder="Type a message..."> <button type="submit">Send</button> </form> </body> </html>

Now, create a new JavaScript file called socket.js in the project root directory:

bash
touch socket.js

Open socket.js and initialize the Socket.IO client:

javascript
const socket = io(); socket.on('connect', () => { console.log('Connected to the server!'); });

Now, update app.py to handle messages from the client:

python
@socketio.on('message') def handle_message(data, message): emit('new_message', data, room=message)

Finally, create a route in app.py for handling WebSocket connections:

python
@socketio.on('connection') def handle_connection(message): join_room(message['room']) print(f'User joined room: {message["room"]}')

Now, let's create a simple Socket.IO example. In the JavaScript code, listen for the form submission and send the message to the server:

javascript
const messageForm = document.getElementById('message-form'); const messageInput = document.getElementById('message'); const messages = document.getElementById('messages'); messageForm.addEventListener('submit', (e) => { e.preventDefault(); const messageText = messageInput.value.trim(); if (messageText) { socket.emit('message', { room: 'chat', text: messageText }); messageInput.value = ''; } });

Now, when a user sends a message, it will be displayed in real-time on the web page.

Quick Quiz
Question 1 of 1

Which line in `app.py` initializes the SocketIO instance?

That's it for our basic Flask-SocketIO tutorial! You now have a solid understanding of how to integrate Socket.IO with Flask to create real-time, interactive web applications. Happy coding! 🚀