Convert Figma logo to code with AI

miguelgrinberg logoFlask-SocketIO

Socket.IO integration for Flask applications.

5,345
888
5,345
8

Top Related Projects

Realtime application framework (client)

67,844

The Python micro framework for building web applications.

8,335

An ASGI web server, for Python. 🦄

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Quick Overview

Flask-SocketIO is a Flask extension that adds WebSocket support to Flask applications using Socket.IO. It allows for real-time, bidirectional communication between the client and server, making it ideal for building interactive web applications and live-updating features.

Pros

  • Easy integration with existing Flask applications
  • Supports both long-polling and WebSocket transports
  • Provides room and namespace functionality for organizing connections
  • Offers event-based communication for intuitive message handling

Cons

  • May introduce additional complexity for simple applications
  • Requires careful handling of concurrent connections in production environments
  • Limited built-in scaling options for large-scale deployments
  • Learning curve for developers new to WebSocket concepts

Code Examples

  1. Basic Flask-SocketIO setup:
from flask import Flask
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('connect')
def handle_connect():
    print('Client connected')

if __name__ == '__main__':
    socketio.run(app)
  1. Emitting events from server to client:
@socketio.on('message')
def handle_message(data):
    print('Received message:', data)
    socketio.emit('response', {'message': 'Server received your message!'})
  1. Joining and leaving rooms:
from flask_socketio import join_room, leave_room

@socketio.on('join')
def on_join(data):
    username = data['username']
    room = data['room']
    join_room(room)
    socketio.emit('status', f'{username} has joined the room.', room=room)

@socketio.on('leave')
def on_leave(data):
    username = data['username']
    room = data['room']
    leave_room(room)
    socketio.emit('status', f'{username} has left the room.', room=room)

Getting Started

  1. Install Flask-SocketIO:

    pip install flask-socketio
    
  2. Create a basic Flask app with SocketIO:

    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):
        print('Received message:', message)
        socketio.emit('response', {'data': 'Server received: ' + message})
    
    if __name__ == '__main__':
        socketio.run(app, debug=True)
    
  3. Create an HTML template with SocketIO client:

    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    </head>
    <body>
        <script>
            var socket = io();
            socket.on('connect', function() {
                socket.emit('message', 'Hello, server!');
            });
            socket.on('response', function(msg) {
                console.log('Server response:', msg.data);
            });
        </script>
    </body>
    </html>
    
  4. Run the app and open it in a web browser to see real-time communication in action.

Competitor Comparisons

Realtime application framework (client)

Pros of socket.io-client

  • Language-agnostic: Can be used with various backend technologies, not limited to Flask
  • More extensive documentation and community support
  • Supports more advanced features like multiplexing and binary data transfer

Cons of socket.io-client

  • Requires separate server-side implementation
  • May have a steeper learning curve for beginners
  • Less integrated with Flask ecosystem

Code Comparison

Flask-SocketIO:

from flask import Flask
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('connect')
def handle_connect():
    emit('response', {'data': 'Connected'})

socket.io-client (JavaScript):

import { io } from "socket.io-client";

const socket = io("http://localhost:5000");

socket.on("connect", () => {
  console.log("Connected to server");
});

Flask-SocketIO provides a more integrated approach for Flask applications, while socket.io-client offers greater flexibility across different backend technologies. Flask-SocketIO simplifies the implementation process for Flask developers, but socket.io-client provides more advanced features and broader language support. The choice between the two depends on the specific project requirements and the developer's familiarity with the Flask ecosystem.

67,844

The Python micro framework for building web applications.

Pros of Flask

  • Core web framework with extensive ecosystem and community support
  • Lightweight and flexible, allowing for easy customization
  • Excellent documentation and learning resources

Cons of Flask

  • Lacks built-in WebSocket support, requiring additional libraries
  • May require more setup and configuration for real-time applications
  • Less specialized for real-time communication compared to Flask-SocketIO

Code Comparison

Flask (basic route):

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World!'

Flask-SocketIO (WebSocket event):

from flask import Flask
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('message')
def handle_message(data):
    emit('response', {'data': 'Received: ' + data})

Flask is a versatile web framework suitable for various applications, while Flask-SocketIO specializes in real-time communication. Flask offers more flexibility but requires additional setup for WebSocket support, whereas Flask-SocketIO provides a streamlined solution for real-time features out of the box.

8,335

An ASGI web server, for Python. 🦄

Pros of Uvicorn

  • High-performance ASGI server with support for HTTP/1.1 and WebSockets
  • Lightweight and easy to integrate with various ASGI frameworks
  • Built-in support for asyncio and uvloop for improved performance

Cons of Uvicorn

  • Requires more setup and configuration for WebSocket functionality
  • Less abstraction for WebSocket handling compared to Flask-SocketIO
  • May require additional libraries for advanced WebSocket features

Code Comparison

Flask-SocketIO:

from flask import Flask
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('connect')
def handle_connect():
    emit('response', {'data': 'Connected'})

Uvicorn with FastAPI:

from fastapi import FastAPI
from fastapi.websockets import WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_text("Connected")

While Flask-SocketIO provides a higher-level abstraction for WebSocket handling, Uvicorn offers more flexibility and performance when used with ASGI frameworks like FastAPI. Flask-SocketIO is easier to set up for WebSocket communication, but Uvicorn's approach allows for more fine-grained control and better scalability in high-performance scenarios.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • Higher performance due to asynchronous capabilities and Starlette framework
  • Built-in API documentation with OpenAPI (Swagger) and ReDoc
  • Type hints and data validation using Pydantic models

Cons of FastAPI

  • Lacks built-in WebSocket support (requires additional libraries)
  • Steeper learning curve for developers new to asynchronous programming
  • Smaller ecosystem compared to Flask and its extensions

Code Comparison

FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Flask-SocketIO:

from flask import Flask
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)

@app.route("/")
def index():
    return "Hello World!"

FastAPI focuses on modern, asynchronous API development with automatic documentation and type checking. Flask-SocketIO, built on Flask, provides a simpler approach with built-in WebSocket support. FastAPI offers better performance and validation, while Flask-SocketIO benefits from Flask's extensive ecosystem and easier WebSocket integration. The choice depends on project requirements, team expertise, and desired features.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Flask-SocketIO

Build status codecov

Socket.IO integration for Flask applications.

Sponsors

The following organizations are funding this project:

Socket.IO
Socket.IO
Add your company here!

Many individual sponsors also support this project through small ongoing contributions. Why not join them?

Installation

You can install this package as usual with pip:

pip install flask-socketio

Example

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
    
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.event
def my_event(message):
    emit('my response', {'data': 'got it!'})

if __name__ == '__main__':
    socketio.run(app)

Resources

NPM DownloadsLast 30 Days