Skip to main content

light and typization Socket.IO server and client for Python

Project description

fastsio (Fast Socket.IO for Python)

Build status codecov

fastsio is a fork of python-socketio with modern Python development improvements inspired by FastAPI.

Key Features

  • Strong typing and FastAPI-like DX with dependency injection
  • Automatic validation of data through Pydantic models
  • Lightweight routers for code organization via RouterSIO
  • Compatibility with existing ASGI/WSGI stacks
  • Full support for the Socket.IO protocol

Installation

pip install fastsio

Key Differences from python-socketio

Feature python-socketio fastsio
Type Safety Minimal Strong typing with annotations
Dependency Injection ✅ FastAPI-style
Pydantic Validation ✅ Automatic
Routers ✅ RouterSIO for code organization
Parameter Annotations SocketID, Environ, Auth, etc.
Compatibility ✅ Full backward compatibility

Quick Start

Simple Server

import fastsio
from fastsio import ASGIApp, SocketID, Environ, Auth, Data

# Create server
sio = fastsio.AsyncServer(
    async_mode="asgi",
    cors_allowed_origins="*"
)

@sio.event
async def connect(
    sid: SocketID, 
    environ: Environ, 
    auth: Auth,
):
    print(f"Client {sid} connected")
    return True

@sio.event
async def disconnect(sid: SocketID):
    print(f"Client {sid} disconnected")

@sio.on("message")
async def handle_message(sid: SocketID, data: Data):
    await sio.emit("response", f"Received: {data}", to=sid)

# ASGI application
app = ASGIApp(sio)

With Type Safety and Dependency Injection

from pydantic import BaseModel
from fastsio import (
    AsyncServer, RouterSIO, SocketID, 
    Environ, Auth, ASGIApp
)

router = RouterSIO()

class Message(BaseModel):
    text: str
    room: str

class JoinRoom(BaseModel):
    room: str

@router.on("connect")
async def on_connect(
    sid: SocketID, 
    environ: Environ, 
    auth: Auth, 
    server: AsyncServer
):
    """Connection with automatic dependency injection"""
    print(f"Connection: {sid}, auth: {auth}")
    return True

@router.on("join_room")
async def on_join_room(
    sid: SocketID, 
    server: AsyncServer, 
    data: JoinRoom  # Automatic Pydantic validation
):
    """Join room with data validation"""
    await server.enter_room(sid, data.room)
    await server.emit("joined", {"room": data.room}, to=sid)

@router.on("send_message")
async def on_send_message(
    sid: SocketID, 
    server: AsyncServer, 
    data: Message
):
    """Send message with validation"""
    await server.emit(
        "new_message", 
        data.model_dump(), 
        room=data.room
    )

# Create server and attach router
sio = AsyncServer(async_mode="asgi", cors_allowed_origins="*")
sio.add_router(router)

app = ASGIApp(sio)

FastAPI Integration

import uvicorn
from fastapi import FastAPI
from fastapi.responses import FileResponse
import fastsio
from fastsio import Environ, Auth, SocketID

app = FastAPI()
sio = fastsio.AsyncServer(async_mode="asgi")

@app.get("/")
async def index():
    return {"message": "FastAPI + fastsio"}

@sio.event
async def connect(sid: SocketID, environ: Environ, auth: Auth):
    await sio.emit("hello", {"message": "Welcome!"}, to=sid)

# Combine FastAPI and Socket.IO
combined_app = fastsio.ASGIApp(sio, app)

if __name__ == "__main__":
    uvicorn.run(combined_app, host="127.0.0.1", port=5000)

Advanced Features

Routers for Code Organization

from fastsio import RouterSIO

# Chat router
chat_router = RouterSIO(namespace="/chat")

@chat_router.on("message")
async def chat_message(sid: SocketID, data: Message):
    # Chat logic
    pass

# Admin router
admin_router = RouterSIO(namespace="/admin")

@admin_router.on("user_ban")
async def ban_user(sid: SocketID, data: BanRequest):
    # Ban logic
    pass

# Attach routers
sio.add_router(chat_router)
sio.add_router(admin_router)

Available Types for Injection

from fastsio import (
    SocketID,    # Connection ID
    Environ,     # WSGI/ASGI environ
    Auth,        # Auth data (connect handler only)
    Reason,      # Disconnect reason (disconnect handler only)
    Data,        # Raw event data
    Event,       # Event name
    AsyncServer  # Server instance
)

@router.on("example")
async def example_handler(
    sid: SocketID,
    server: AsyncServer,
    environ: Environ,
    data: Data,
    event: Event
):
    print(f"Event {event} from {sid}: {data}")

Version Compatibility

Compatibility table with JavaScript Socket.IO:

JavaScript Socket.IO Socket.IO protocol Engine.IO protocol fastsio version
0.9.x 1, 2 1, 2 Not supported
1.x and 2.x 3, 4 3 Any version
3.x and 4.x 5 4 Any version

Documentation

Contributing

fastsio is based on the excellent work by Miguel Grinberg on python-socketio. We've added modern capabilities while maintaining full compatibility with the original API.

License

MIT License - see LICENSE file


🌍 Other Languages: Русский

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastsio-0.3.1.tar.gz (74.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastsio-0.3.1-py3-none-any.whl (90.6 kB view details)

Uploaded Python 3

File details

Details for the file fastsio-0.3.1.tar.gz.

File metadata

  • Download URL: fastsio-0.3.1.tar.gz
  • Upload date:
  • Size: 74.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for fastsio-0.3.1.tar.gz
Algorithm Hash digest
SHA256 7b01fc4915780bbfd7f8bfbf921b0c74f03faa7d18a4ddb292192625a0f249f8
MD5 7a6f6925d4f519a82da888bb95fedfd3
BLAKE2b-256 ad1953ce87b6b0cdfca278c0f8288e94c8de37425f1ed4c2ccd2c7c8c2751082

See more details on using hashes here.

File details

Details for the file fastsio-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: fastsio-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 90.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for fastsio-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 bcf960e15f4eff5263309504ce06d65cb45aa941aa3d6ee5acbc9b510d21b1ec
MD5 8cc1e3a8de54507a36066ceeb0e2f5ee
BLAKE2b-256 0b644dfc80c71cd3d63733c545616928a515ee44098b2d0da5af9693e77be46f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page