Flask-Sock

0.7.0 · active · verified Sat Apr 11

Flask-Sock provides WebSocket support for Flask applications, enabling real-time, bi-directional communication. Unlike other solutions, it works directly with the Flask development web server and does not require a greenlet-based server like gevent or eventlet for basic operation. It is also compatible with production WSGI servers such as Gunicorn (with threading), Eventlet, or Gevent. The current version is 0.7.0, with a periodic release cadence.

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic Flask application with a WebSocket endpoint that echoes back any received message. Instantiate `Flask` and `Sock`, then use the `@sock.route()` decorator to define WebSocket handlers. The `ws` object within the handler provides `receive()` and `send()` methods for communication.

from flask import Flask
from flask_sock import Sock
import os

app = Flask(__name__)
sock = Sock(app)

@app.route('/')
def index():
    return 'Hello, Flask-Sock!'

@sock.route('/echo')
def echo(ws):
    while True:
        data = ws.receive()
        if data is None: # Client disconnected
            break
        print(f"Received: {data}")
        ws.send(data)

if __name__ == '__main__':
    # For development, Flask's built-in server works. 
    # For production, use Gunicorn with --threads, Eventlet, or Gevent.
    app.run(debug=True)

view raw JSON →