Flask-Sock
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
- breaking Version 0.4.0 of `flask-sock` and newer explicitly introduced a dependency on `Flask 2.x`. Applications using these versions must ensure they are running Flask 2.0.0 or higher, as older Flask versions are no longer supported.
- gotcha When deploying `flask-sock` applications with Gunicorn, each active WebSocket connection consumes a worker process by default. To efficiently handle multiple concurrent WebSocket clients, Gunicorn must be configured to use threads (e.g., `gunicorn -b :5000 --threads 100 module:app`).
- gotcha As of version 0.5.2, WebSocket server options, such as `ping_interval` and `max_message_size`, can be configured via `app.config['SOCK_SERVER_OPTIONS']`. Failing to set `ping_interval` (e.g., to 25 seconds) can lead to unexpected disconnections for idle WebSocket connections due to proxy timeouts.
Install
-
pip install flask-sock
Imports
- Sock
from flask_sock import Sock
- Flask
from flask import Flask
Quickstart
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)