FLASK-SOCKETIO(1)
๐ฆ FLASK-SOCKETIO ๐ฆ
okay bestie, sit down, hydrate, and let's get into it โ this is the manual page for flask-socketio, and it's lowkey iconic ๐
๐ NAME ๐
flask-socketio โ the flask-socketio Documentation, periodt.
Flask-SocketIO gives your Flask apps access to low latency bi-directional communications between the clients and the server ๐ซถ. The client-side app can use literally any of the SocketIO client libraries โ Javascript, Python, C++, Java and Swift (http://socket.io), or any other compatible client โ to establish a permanent connection to the server. no cap.
๐ธ INTRODUCTION ๐ธ
๐ Installation ๐
you install this package the usual way, with pip:
pip install flask-socketio
๐ง Requirements ๐ง
Flask-SocketIO is compatible with Python 3.6+. The asynchronous services that this package relies on can be selected among three choices:
eventlet(http://eventlet.net/) โ the best performant option, with support for long-polling and WebSocket transports. slay ๐gevent(http://www.gevent.org/) โ supported in a number of different configurations. The long-polling transport is fully supported with the gevent package, but unlike eventlet, gevent does not have native WebSocket support. To add WebSocket support there are currently two options: installing thegevent-websocketpackage (https://pypi.python.org/pypi/gevent-websocket/) adds WebSocket support to gevent, or you can use theuWSGIweb server (https://uwsgi-docs.readthedocs.io/en/latest/), which comes with WebSocket functionality. The use of gevent is also a performant option, just slightly lower than eventlet.- The Flask development server based on Werkzeug โ can be used as well, with the caveat that this web server is intended only for development use, so it should only be used to simplify the development workflow and not for production. ๐
The extension automatically detects which asynchronous framework to use based on what is installed. Preference is given to eventlet, followed by gevent. For WebSocket support in gevent, uWSGI is preferred, followed by gevent-websocket. If neither eventlet nor gevent are installed, then the Flask development server is used.
If you're using multiple processes, a message queue service must be configured so the servers can coordinate operations like broadcasting ๐ข. The supported queues are Redis (http://redis.io/), RabbitMQ (https://www.rabbitmq.com/), Kafka (http://kafka.apache.org/), and any other message queues supported by the Kombu package (http://kombu.readthedocs.org/en/latest/).
On the client-side, the official Socket.IO Javascript client library can be used to establish a connection to the server. There are also official clients written in Swift, Java and C++. Unofficial clients may also work, as long as they implement the Socket.IO protocol (https://github.com/socketio/socket.io-protocol). The python-socketio package (https://github.com/miguelgrinberg/python-socketio) โ which provides the Socket.IO server implementation used by Flask-SocketIO โ includes a Python client. ๐
๐ Version compatibility ๐
The Socket.IO protocol has been through a number of revisions, and some of these introduced backward incompatible changes, which means the client and the server must use compatible versions for everything to work. fr fr, don't skip this part.
The version compatibility chart below maps versions of this package to versions of the JavaScript reference implementation and the versions of the Socket.IO and Engine.IO protocols. (the original was a big ol' table, so here it is as a glow-up list โจ)
- JavaScript Socket.IO version
0.9.x- Socket.IO protocol revision:
1, 2 - Engine.IO protocol revision:
1, 2 - Flask-SocketIO version:
Not supported - python-socketio version:
Not supported - python-engineio version:
Not supported
- Socket.IO protocol revision:
- JavaScript Socket.IO version
1.x and 2.x- Socket.IO protocol revision:
3, 4 - Engine.IO protocol revision:
3 - Flask-SocketIO version:
4.x - python-socketio version:
4.x - python-engineio version:
3.x
- Socket.IO protocol revision:
- JavaScript Socket.IO version
3.x and 4.x- Socket.IO protocol revision:
5 - Engine.IO protocol revision:
4 - Flask-SocketIO version:
5.x - python-socketio version:
5.x - python-engineio version:
4.x
- Socket.IO protocol revision:
โญ GETTING STARTED โญ
๐ฆ Initialization ๐ฆ
The following code example shows how to add Flask-SocketIO to a Flask application:
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
if __name__ == '__main__':
socketio.run(app)
The init_app() style of initialization is also supported:
from flask import Flask, render_template
from flask_socketio import SocketIO
socketio = SocketIO()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio.init_app(app)
return app
if __name__ == '__main__':
app = create_app()
socketio.run(app)
To start the web server simply execute your script. Note the way the web server is started ๐. The socketio.run() function encapsulates the start up of the web server and replaces the app.run() standard Flask development server start up. When the application is in debug mode the Werkzeug development server is still used and configured properly inside socketio.run(). In production mode the eventlet web server is used if available, else the gevent web server is used. If eventlet and gevent are not installed, the Werkzeug development web server is used.
The flask run command introduced in Flask 0.11 can be used to start a Flask-SocketIO development server based on Werkzeug, but this method of starting the Flask-SocketIO server is not recommended due to lack of WebSocket support ๐ญ. Previous versions of this package included a customized version of the flask run command that allowed the use of WebSocket on eventlet and gevent production servers, but this functionality has been discontinued in favor of the socketio.run(app) startup method shown above, which is more robust.
The application must serve a page to the client that loads the Socket.IO library and establishes a connection:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
var socket = io();
socket.on('connect', function() {
socket.emit('my event', {data: 'I\'m connected!'});
});
</script>
๐ซถ Receiving Messages ๐ซถ
When using SocketIO, messages are received by both parties as events. On the client side Javascript callbacks are used. With Flask-SocketIO the server needs to register handlers for these events, similarly to how routes are handled by view functions.
The following example creates a server-side event handler for an unnamed event:
@socketio.on('message')
def handle_message(data):
print('received message: ' + data)
The above example uses string messages. Another type of unnamed events use JSON data:
@socketio.on('json')
def handle_json(json):
print('received json: ' + str(json))
The most flexible type of event uses custom event names. The message data for these events can be string, bytes, int, or JSON:
@socketio.on('my event')
def handle_my_custom_event(json):
print('received json: ' + str(json))
Custom named events can also support multiple arguments:
@socketio.on('my_event')
def handle_my_custom_event(arg1, arg2, arg3):
print('received args: ' + arg1 + arg2 + arg3)
When the name of the event is a valid Python identifier that does not collide with other defined symbols, the @socketio.event decorator provides a more compact syntax that takes the event name from the decorated function:
@socketio.event
def my_custom_event(arg1, arg2, arg3):
print('received args: ' + arg1 + arg2 + arg3)
Named events are the most flexible, as they eliminate the need to include additional metadata to describe the message type. The names message, json, connect and disconnect are reserved and cannot be used for named events. ๐ซ
Flask-SocketIO also supports SocketIO namespaces, which allow the client to multiplex several independent connections on the same physical socket:
@socketio.on('my event', namespace='/test')
def handle_my_custom_namespace_event(json):
print('received json: ' + str(json))
When a namespace is not specified a default global namespace with the name '/' is used.
For cases when a decorator syntax isn't convenient, the on_event method can be used:
def my_function_handler(data):
pass
socketio.on_event('my event', my_function_handler, namespace='/test')
Clients may request an acknowledgement callback that confirms receipt of a message they sent. Any values returned from the handler function will be passed to the client as arguments in the callback function:
@socketio.on('my event')
def handle_my_custom_event(json):
print('received json: ' + str(json))
return 'one', 2
In the above example, the client callback function will be invoked with two arguments, 'one' and 2. If a handler function does not return any values, the client callback function will be invoked without arguments.
๐ Sending Messages ๐
SocketIO event handlers defined as shown in the previous section can send reply messages to the connected client using the send() and emit() functions.
The following examples bounce received events back to the client that sent them:
from flask_socketio import send, emit
@socketio.on('message')
def handle_message(message):
send(message)
@socketio.on('json')
def handle_json(json):
send(json, json=True)
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json)
okay so bestie, clock the difference: send() is for the unnamed events and emit() is for the named ones. That's literally it. That's the whole vibe. ๐
When you're doing namespace stuff, send() and emit() just default to the namespace of whatever message came in โ no extra work needed. But if you wanna aim somewhere else, there's an optional namespace argument you can hand them:
@socketio.on('message')
def handle_message(message):
send(message, namespace='/chat')
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json, namespace='/chat')
Wanna yeet an event out with multiple arguments? Just send a tuple, no cap:
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', ('foo', 'bar', json), namespace='/chat')
๐ธ Acknowledgment Callbacks ๐ธ
SocketIO also does acknowledgment callbacks, which are basically the client going "got it, received ur message bestie" โจ
def ack():
print('message was received!')
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json, callback=ack)
Here's the tea: when you use callbacks, the JavaScript client gets handed a callback function to invoke once the message lands. After the client app calls that function, the server then calls the matching server-side callback. And if the client-side callback got invoked with arguments, those same arguments show up as arguments to the server-side callback too. symmetry, we love to see it ๐
๐ก Broadcasting ๐ก
Broadcasting is genuinely one of the most useful things SocketIO does. Flask-SocketIO serves it up with the optional broadcast=True argument on send() and emit():
@socketio.on('my event')
def handle_my_custom_event(data):
emit('my response', data, broadcast=True)
So when a message goes out with the broadcast option on, every client connected to the namespace gets it โ including the one who sent it. If you're not using namespaces, then it's the clients connected to the global namespace who receive it. And heads up: callbacks do not get invoked for broadcast messages. Not a thing. ๐ โโ๏ธ
Now, every example so far has the server replying to a client event. But some apps need the server to be the one starting the convo โ like sending notifications about stuff that happened server-side, say from a background thread. For that, the socketio.send() and socketio.emit() methods broadcast to all connected clients:
def some_function():
socketio.emit('some event', {'data': 42})
careful bestie โ ๏ธ โsocketio.send()andsocketio.emit()are not the same functions as the context-awaresend()andemit(). Different creatures, same-ish names. Also, in that usage up there there's no client context at all, sobroadcast=Trueis just assumed and you don't need to type it out. ๐ฆ
๐ช Rooms ๐ช
Sometimes you gotta group users into little subsets you can address together. The iconic example is a chat app with multiple rooms โ people get messages from the room(s) they're in and not from the rooms they're not in. Flask-SocketIO does this with join_room() and leave_room():
from flask_socketio import join_room, leave_room
@socketio.on('join')
def on_join(data):
username = data['username']
room = data['room']
join_room(room)
send(username + ' has entered the room.', to=room)
@socketio.on('leave')
def on_leave(data):
username = data['username']
room = data['room']
leave_room(room)
send(username + ' has left the room.', to=room)
send() and emit() take an optional to argument that makes the message go to all the clients sitting in that given room. โจ
Here's how it actually works: every client gets assigned a room the moment they connect, and that room is named after the session ID of the connection โ you can grab it from request.sid. A client can join whatever rooms it wants, and those rooms can be named literally anything. When a client disconnects, it gets removed from all the rooms it was in. The context-free socketio.send() and socketio.emit() functions also accept a to argument so you can broadcast to everyone in a room from outside a request context.
And because everybody has that personal room, if you wanna slide a message to exactly one client, just use their session ID as the to argument. chef's kiss ๐
๐ Connection Events ๐
Flask-SocketIO also dispatches connection and disconnection events. Registering handlers for them looks like this:
@socketio.on('connect')
def test_connect(auth):
emit('my response', {'data': 'Connected'})
@socketio.on('disconnect')
def test_disconnect(reason):
print('Client disconnected, reason:', reason)
The auth argument in the connection handler is optional. The client can use it to pass authentication data like tokens, in dictionary format. If the client sends no auth details, this argument is just None. And if the server defines a connection handler without that argument, then any auth data the client sent gets discarded. poof. gone. ๐
The connection handler can return False to reject the connection, or it can raise ConnectionRefusedError. This is so you can authenticate the client right at that point. When you use the exception, whatever arguments you pass to it get returned to the client in the error packet. Like so:
from flask_socketio import ConnectionRefusedError
@socketio.on('connect')
def connect():
if not self.authenticate(request.args):
raise ConnectionRefusedError('unauthorized!')
The disconnection handler receives a reason argument telling you why the disconnect happened. The flask_socketio.SocketIO.reason member holds constants for all the possible reasons. ๐
And ngl, important detail: connection and disconnection events are sent individually on each namespace that's in use. Not once globally. iykyk.
๐ Class-Based Namespaces ๐
Instead of decorating functions, you can write your event handlers as methods of a class. flask_socketio.Namespace is the base class you build on:
from flask_socketio import Namespace, emit
class MyCustomNamespace(Namespace):
def on_connect(self):
pass
def on_disconnect(self, reason):
pass
def on_my_event(self, data):
emit('my_response', data)
socketio.on_namespace(MyCustomNamespace('/test'))
When you go the class-based route, any event the server receives gets dispatched to a method named after the event with an on_ prefix. So for example event my_event gets handled by a method called on_my_event. If an event comes in and there's no matching method on the namespace class, the event is just ignored. And every event name you use in a class-based namespace has to use characters that are legal in method names โ no wild choices. ๐ซ
Little convenience for ya: methods defined in a class-based namespace get namespace instances that include versions of several methods from the flask_socketio.SocketIO class, and those default to the proper namespace whenever the namespace argument isn't given. ๐ซถ
heads up โ if an event has a handler in a class-based namespace and a decorator-based function handler, only the decorated function handler runs. The other one just sits there. ๐
๐ Error Handling ๐
Flask-SocketIO can catch exceptions too:
@socketio.on_error() # Handles the default namespace
def error_handler(e):
pass
@socketio.on_error('/chat') # handles the '/chat' namespace
def error_handler_chat(e):
pass
@socketio.on_error_default # handles all namespaces without an explicit error handler
def default_error_handler(e):
pass
Error handler functions take the exception object as their argument. That's the whole signature bestie. ๐
You can also peek at the message and data arguments of the current request through the request.event variable โ super useful for error logging and debugging outside the event handler:
from flask import request
@socketio.on("my error event")
def on_my_event(data):
raise RuntimeError()
@socketio.on_error_default
def default_error_handler(e):
print(request.event["message"]) # "my error event"
print(request.event["args"]) # (data,)
๐ Debugging and Troubleshooting ๐
To help you debug stuff, the server can be configured to dump logs to the terminal:
socketio = SocketIO(logger=True, engineio_logger=True)
logger controls logging related to the Socket.IO protocol, while engineio_logger controls logs coming from the low-level Engine.IO transport. Set them to True to output logs to stderr, or hand them an object compatible with Python's logging package to control where the logs get emitted. False disables logging entirely.
Logging is genuinely your bestie when you're trying to figure out connection problems, 400 responses, bad performance, and other mysterious issues. vibe check your logs first, always โจ
๐ ๏ธ IMPLEMENTATION NOTES ๐ ๏ธ
๐ง Access to Flask's Context Globals
okay bestie this is THE section where people get confused, so listen up ๐ Handlers for SocketIO events are not the same as handlers for routes, and that one tiny fact is what makes everybody lose their minds about what you can and cannot do inside a SocketIO handler. The main difference? Every single SocketIO event generated for a client happens inside the context of one single long-running request. One. Long. Request. ๐ญ
Even with all that chaos, Flask-SocketIO is out here trying its absolute best to make SocketIO event handlers feel like a regular HTTP request so your brain doesn't have to hold two mental models at once. Here's the rundown of what works and what does not work:
- An application context is pushed before invoking an event handler, which makes
current_appandgavailable to the handler. slay โจ - A request context is also pushed before invoking a handler, which also makes
requestandsessionavailable. BUT โ and this is the plot twist โ WebSocket events do not have individual requests associated with them, so the request context that started the connection gets pushed for all the events dispatched during the life of that connection. it's giving "one context to rule them all" ๐ - The request context global is enhanced with a
sidmember that's set to a unique session ID for the connection. This value is used as the initial room where the client is added. iconic. - The request context global is enhanced with
namespaceandeventmembers that contain the currently handled namespace and event arguments. Theeventmember is a dictionary withmessageandargskeys. very demure, very mindful ๐ธ - The
sessioncontext global behaves differently than it does in regular requests, and this is the part that catches everyone. A copy of the user session at the time the SocketIO connection is established is made available to handlers invoked in the context of that connection. If a SocketIO handler modifies the session, the modified session will be preserved for future SocketIO handlers โ but regular HTTP route handlers will not see these changes. Effectively, when a SocketIO handler modifies the session, a "fork" of the session is created exclusively for these handlers. The technical reason for this limitation is that to save the user session, a cookie needs to be sent to the client, and that requires an HTTP request and response, which do not exist in a SocketIO connection. When you're using server-side sessions like the ones provided by the Flask-Session or Flask-KVSession extensions, changes made to the session in HTTP route handlers can be seen by SocketIO handlers, as long as the session is not modified in the SocketIO handlers. no cap, that's just how it is ๐ - The
before_requestandafter_requesthooks are not invoked for SocketIO event handlers. not even a little bit. - SocketIO handlers can take custom decorators, but most Flask decorators will not be appropriate to use for a SocketIO handler, given that there is no concept of a
Responseobject during a SocketIO connection. so likeโฆ keep the Flask decorators for the Flask routes, bestie ๐
๐ Authentication
A super common need for applications is validating the identity of their users. The traditional mechanisms based on web forms and HTTP requests cannot be used in a SocketIO connection, since there is literally no place to send HTTP requests and responses. Nowhere. Doesn't exist. If you absolutely need to, an application can implement a customized login form that sends credentials to the server as a SocketIO message when the submit button is pressed by the user. custom โจ
But honestly? In most cases it's way more convenient to do the traditional authentication process before the SocketIO connection is established. Then the user's identity can be recorded in the user session or in a cookie, and later when the SocketIO connection is established, that information will be accessible to SocketIO event handlers. easy peasy ๐
Recent revisions of the Socket.IO protocol include the ability to pass a dictionary with authentication information during the connection. This is an ideal place for the client to include a token or other authentication details. If the client uses this capability, the server will provide this dictionary as an argument to the connect event handler, as shown above. ๐
๐ซถ Using Flask-Login with Flask-SocketIO
Flask-SocketIO can access login information maintained by Flask-Login (https://flask-login.readthedocs.org/en/latest/). After a regular Flask-Login authentication is performed and the login_user() function is called to record the user in the user session, any SocketIO connections will have access to the current_user context variable:
@socketio.on('connect')
def connect_handler():
if current_user.is_authenticated:
emit('my response',
{'message': '{0} has joined'.format(current_user.name)},
broadcast=True)
else:
return False # not allowed here
Heads up bestie โ the login_required decorator cannot be used with SocketIO event handlers. ๐ญ But you can absolutely create a custom decorator that disconnects non-authenticated users, like this:
import functools
from flask import request
from flask_login import current_user
from flask_socketio import disconnect, emit
def authenticated_only(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
if not current_user.is_authenticated:
disconnect()
else:
return f(*args, **kwargs)
return wrapped
@socketio.on('my event')
@authenticated_only
def handle_my_custom_event(data):
emit('my response', {'message': '{0} has joined'.format(current_user.name)},
broadcast=True)
๐ DEPLOYMENT ๐
There are so many options for deploying a Flask-SocketIO server, ranging from simple to the insanely complex. ๐ In this section we're covering the most commonly used ones, so let's go.
๐ฃ Embedded Server
The simplest deployment strategy is to start the web server by calling socketio.run(app) as shown in the examples above. This will look through the packages that are installed for the best available web server and start the application on it. The current web server choices that are evaluated are eventlet, gevent and the Flask development server.
If eventlet or gevent are available, socketio.run(app) starts a production-ready server using one of these frameworks. If neither of these are installed, then the Flask development web server is used โ and in that case, the server is not intended to be used in a production deployment. please don't ship the dev server, bestie, I'm begging ๐
Unfortunately, this option is not available when using gevent with uWSGI. See the uWSGI section below for information on this option.
๐ฆ Gunicorn Web Server
An alternative to socketio.run(app) is to use gunicorn (http://gunicorn.org/) as web server, using the eventlet or gevent workers. For this option, eventlet or gevent need to be installed, in addition to gunicorn. The command line that starts the eventlet server via gunicorn is:
gunicorn --worker-class eventlet -w 1 module:app
If you prefer to use gevent, the command to start the server is:
gunicorn -k gevent -w 1 module:app
When using gunicorn with the gevent worker and the WebSocket support provided by gevent-websocket, the command that starts the server must be changed to select a custom gevent web server that supports the WebSocket protocol. The modified command is:
gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 module:app
A third option with Gunicorn is to use the threaded worker, along with the simple-websocket package (https://github.com/miguelgrinberg/simple-websocket) for WebSocket support. This is a particularly good solution for applications that are CPU heavy or are otherwise incompatible with eventlet and gevent use of green threads. The command to start a threaded web server is:
gunicorn -w 1 --threads 100 module:app
In all these commands, module is the Python module or package that defines the application instance, and app is the application instance itself. don't forget that part ๐
Due to the limited load balancing algorithm used by gunicorn, it is not possible to use more than one worker process when using this web server. For that reason, all the examples above include the -w 1 option.
The workaround to use multiple worker processes with gunicorn is to launch several single-worker instances and put them behind a more capable load balancer such as nginx (https://www.nginx.com/). slay ๐ฆ
๐ uWSGI Web Server
When using the uWSGI server in combination with gevent, the Socket.IO server can take advantage of uWSGI's native WebSocket support. ๐ฅ
A complete explanation of the configuration and usage of the uWSGI server is beyond the scope of this documentation. The uWSGI server is a fairly complex package that provides a large and comprehensive set of options. It must be compiled with WebSocket and SSL support for the WebSocket transport to be available. As way of an introduction, the following command starts a uWSGI server for the example application app.py on port 5000:
$ uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file app.py --callable app
๐ Using nginx as a WebSocket Reverse Proxy
It is possible to use nginx as a front-end reverse proxy that passes requests to the application. However โ and this is important โ only releases of nginx 1.4 and newer support proxying of the WebSocket protocol. Below is a basic nginx configuration that proxies HTTP and WebSocket requests:
server {
listen 80;
server_name _;
location / {
include proxy_params;
proxy_pass http://127.0.0.1:5000;
}
location /static/ {
alias <path-to-your-application>/static/;
expires 30d;
}
location /socket.io {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://127.0.0.1:5000/socket.io;
}
}
The next example adds the support for load balancing multiple Socket.IO servers:
upstream socketio_nodes {
ip_hash;
server 127.0.0.1:5000;
server 127.0.0.1:5001;
server 127.0.0.1:5002;
# to scale the app, just add more nodes here!
}
server {
listen 80;
server_name _;
location / {
include proxy_params;
proxy_pass http://127.0.0.1:5000;
}
location /static/ {
alias <path-to-your-application>/static/;
expires 30d;
}
location /socket.io {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://socketio_nodes/socket.io;
}
}
Okay so real talk bestie โ those nginx examples up there? They're a vibe, they're a starting point, they work as an initial configuration. But a production install of nginx is gonna need a more complete configuration that covers other deployment aspects too, like SSL support. โจ Not optional, just saying.
๐ Using Multiple Workers
Flask-SocketIO supports multiple workers behind a load balancer starting with release 2.0. And why do we care? Because deploying multiple workers gives applications that use Flask-SocketIO the ability to spread the client connections among multiple processes and hosts, and in this way scale to support very large numbers of concurrent clients. Iconic. ๐
There are two requirements to use multiple Flask-SocketIO workers:
- The load balancer must be configured to forward all HTTP requests from a given client always to the same worker. This is sometimes referenced as "sticky sessions". For nginx, use the
ip_hashdirective to achieve this. Gunicorn cannot be used with multiple workers because its load balancer algorithm does not support sticky sessions. ๐ซ - Since each of the servers owns only a subset of the client connections, a message queue such as Redis or RabbitMQ is used by the servers to coordinate complex operations such as broadcasting and rooms. No queue, no coordination, that's just how it is. ๐โโ๏ธ
When working with a message queue, there are additional dependencies that need to be installed:
- For Redis, the package
redismust be installed (pip install redis). - For RabbitMQ, the package
kombumust be installed (pip install kombu). - For Kafka, the package
kafka-pythonmust be installed (pip install kafka-python). - For other message queues supported by Kombu, see the Kombu documentation
http://docs.celeryproject.org/projects/kombu/en/latest/introduction.html#transport-comparisonto find out what dependencies are needed. - If eventlet or gevent are used, then monkey patching the Python standard library is normally required to force the message queue package to use coroutine friendly functions and classes. ๐
For eventlet, monkey patching is done with:
import eventlet
eventlet.monkey_patch()
For gevent, you can monkey patch the standard library with:
from gevent import monkey
monkey.patch_all()
In both cases it is recommended that you apply the monkey patching at the top of your main script, even above your imports. Like, the very top. Before everything. Yes really. ๐
To start multiple Flask-SocketIO servers, you must first ensure you have the message queue service running. To start a Socket.IO server and have it connect to the message queue, add the message_queue argument to the SocketIO constructor:
socketio = SocketIO(app, message_queue='redis://')
The value of the message_queue argument is the connection URL of the queue service that is used. For a redis queue running on the same host as the server, the 'redis://' URL can be used. Likewise, for a default RabbitMQ queue the 'amqp://' URL can be used. For Kafka, use a kafka:// URL. The Kombu package has a documentation section http://docs.celeryproject.org/projects/kombu/en/latest/userguide/connections.html?highlight=urls#urls that describes the format of the URLs for all the supported queues. ๐ฎ
๐ค Emitting from an External Process
For many types of applications, it is necessary to emit events from a process that is not the SocketIO server โ for an example a Celery worker. If the SocketIO server or servers are configured to listen on a message queue as shown in the previous section, then any other process can create its own SocketIO instance and use it to emit events in the same way the server does. ๐ฆ
For example, for an application that runs on an eventlet web server and uses a Redis message queue, the following Python script broadcasts an event to all clients:
socketio = SocketIO(message_queue='redis://')
socketio.emit('my event', {'data': 'foo'}, namespace='/test')
When using the SocketIO instance in this way, the Flask application instance is not passed to the constructor. Nope, not there. Not invited. ๐
The channel argument to SocketIO can be used to select a specific channel of communication through the message queue. Using a custom channel name is necessary when there are multiple independent SocketIO services sharing the same queue. Keep your channels separate, besties, it's giving boundaries. ๐
Flask-SocketIO does not apply monkey patching when eventlet or gevent are used. But when working with a message queue, it is very likely that the Python package that talks to the message queue service will hang if the Python standard library is not monkey patched. ๐ญ So yeah, patch it yourself.
It is important to note that an external process that wants to connect to a SocketIO server does not need to use eventlet or gevent like the main server. Having a server use a coroutine framework, while an external process is not, is not a problem. For example, Celery workers do not need to be configured to use eventlet or gevent just because the main server does. But if your external process does use a coroutine framework for whatever reason, then monkey patching is likely required, so that the message queue accesses coroutine friendly functions and classes. ๐
๐ก๏ธ Cross-Origin Controls
For security reasons, this server enforces a same-origin policy by default. In practical terms, this means the following:
- If an incoming HTTP or WebSocket request includes the
Originheader, this header must match the scheme and host of the connection URL. In case of a mismatch, a400status code response is returned and the connection is rejected. ๐ซ - No restrictions are imposed on incoming requests that do not include the
Originheader.
If necessary, the cors_allowed_origins option can be used to allow other origins. This argument can be set to a string to set a single allowed origin, or to a list to allow multiple origins. A special value of '*' can be used to instruct the server to allow all origins โ but this should be done with care, as this could make the server vulnerable to Cross-Site Request Forgery (CSRF) attacks. ๐
โ ๏ธ Fr fr, be careful with '*'. Convenient? Yes. Safe? Absolutely not. That's a CSRF vulnerability, no cap.
๐ UPGRADING TO FLASK-SOCKETIO 5.X FROM THE 4.X RELEASES
The Socket.IO protocol recently introduced a series of backwards incompatible changes. The 5.x releases of Flask-SocketIO adopted these changes, and for that reason it can only be used with clients that have also been updated to the current version of the protocol. In particular, this means that the JavaScript client must be upgraded to a 3.x release, and if your client hasn't been upgraded to the latest version of the Socket.IO protocol, then you must use a Flask-SocketIO 4.x release. Choose your fighter, but they have to match. ๐ฏโโ๏ธ
The following protocol changes are of importance, as they may affect existing applications:
- The default namespace
'/'is not automatically connected anymore, and is now treated in the same way as other namespaces. - Each namespace connection has its own
sidvalue, different from the others and different from the Engine.IOsid. - Flask-SocketIO now uses the same ping interval and timeout values as the JavaScript reference implementation, which are
25and5seconds respectively. - The ping/pong mechanism has been reversed. In the current version of the protocol, the server issues a ping and the client responds with a pong. ๐
- The default allowed payload size for long-polling packets has been lowered from
100MBto1MB. - The
iocookie is not sent to the client anymore by default. ๐ชโ๏ธ
๐ API REFERENCE
- Index
<> - Module Index
<> - Search Page
<>
๐ AUTHOR
Miguel Grinberg
๐ COPYRIGHT
2018, Miguel Grinberg
And that's a wrap on the whole thing, bestie ๐ซถ This page is from Dec 31, 2025, and you've officially made it through FLASK-SOCKETIO(1) โ every last bit. Go build something slay. ๐โจ
๐ฆ where this page comes from
- ubuntu resolute: python3-flask-socketio 5.6.0-1ubuntu1 ยท MIT
- ubuntu stonking: python3-flask-socketio 5.6.1-0.1 ยท MIT
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms