APIReference—Flask-SocketIOdocumentation_1737521229223
APIReference—Flask-SocketIOdocumentation_1737521229223
Parameters: app – The flask application instance. If the application instance isn’t known
at the time this class is instantiated, then call socketio.init_app(app) once
the application instance is available.
manage_session – If set to True, this extension manages the user session for
Socket.IO events. If set to False, Flask’s own session management is used.
When using Flask’s cookie based sessions it is recommended that you leave
this set to the default of True. When using server-side sessions, a False set-
ting enables sharing the user session between HTTP routes and Socket.IO
events.
message_queue – A connection URL for a message queue service the server
can use for multi-process communication. A message queue is not required
when using a single server process.
channel – The channel name, when using a message queue. If a channel isn’t
specified, a default channel will be used. If multiple clusters of SocketIO pro-
cesses need to use the same message queue without interfering with each
other, then each cluster should use a different channel.
path – The path where the Socket.IO server is exposed. Defaults to
'socket.io'. Leave this as is unless you know what you are doing.
resource – Alias to path.
kwargs – Socket.IO and Engine.IO server options.
Parameters: client_manager – The client manager instance that will manage the client
list. When this is omitted, the client list is stored in an in-memory structure,
so the use of multiple connected servers is not possible. In most cases, this ar-
gument does not need to be set explicitly.
logger – To enable logging set to True or pass a logger object to use. To dis-
able logging set to False. The default is False. Note that fatal errors will be
logged even when logger is False.
json – An alternative json module to use for encoding and decoding packets.
Custom json modules must have dumps and loads functions that are compati-
ble with the standard library versions. To use the same json encoder and de-
coder as a Flask application, use flask.json.
async_handlers – If set to True, event handlers for a client are executed in
separate threads. To run handlers for a client synchronously, set to False.
The default is True.
always_connect – When set to False, new connections are provisory until
the connect handler returns something other than False, at which point they
are accepted. When set to True, connections are immediately accepted, and
then if the connect handler returns False a disconnect is issued. Set to True if
you need to emit events from the connect handler and your client is con-
fused when it receives events before the connection acceptance. In any other
case use the default of False.
Parameters: async_mode – The asynchronous model to use. See the Deployment section
in the documentation for a description of the available options. Valid async
modes are threading, eventlet, gevent and gevent_uwsgi. If this argument is
not given, eventlet is tried first, then gevent_uwsgi, then gevent, and finally
threading. The first async mode that has all its dependencies installed is then
one that is chosen.
ping_interval – The interval in seconds at which the server pings the client.
The default is 25 seconds. For advanced control, a two element tuple can be
given, where the first number is the ping interval and the second is a grace
period added by the server.
ping_timeout – The time in seconds that the client waits for the server to re-
spond before disconnecting. The default is 5 seconds.
max_http_buffer_size – The maximum size of a message when using the
polling transport. The default is 1,000,000 bytes.
allow_upgrades – Whether to allow transport upgrades or not. The default is
True.
http_compression – Whether to compress packages when using the polling
transport. The default is True.
compression_threshold – Only compress messages when their byte size is
greater than this value. The default is 1024 bytes.
cookie – If set to a string, it is the name of the HTTP cookie the server sends
back to the client containing the client session id. If set to a dictionary, the
'name' key contains the cookie name and other keys define cookie attributes,
where the value of each attribute can be a string, a callable with no argu-
ments, or a boolean. If set to None (the default), a cookie is not sent to the
client.
cors_allowed_origins – Origin or list of origins that are allowed to connect
to this server. Only the same origin is allowed by default. Set this argument
to '*' to allow all origins, or to [] to disable CORS handling.
cors_credentials – Whether credentials (cookies, authentication) are al-
lowed in requests to this server. The default is True.
monitor_clients – If set to True, a background task will ensure inactive
clients are closed. Set to False to disable the monitoring task (not recom-
mended). The default is True.
engineio_logger – To enable Engine.IO logging set to True or pass a logger
object to use. To disable logging set to False. The default is False. Note that
fatal errors are logged even when engineio_logger is False.
class reason
Disconnection reasons.
on(message, namespace=None)
Decorator to register a SocketIO event handler.
Parameters: message – The name of the event. This is normally a user defined string,
but a few event names are already defined. Use 'message' to define a
handler that takes a string payload, 'json' to define a handler that takes
a JSON blob payload, 'connect' or 'disconnect' to create handlers for
connection and disconnection events.
namespace – The namespace on which the handler is to be registered.
Defaults to the global namespace.
on_error(namespace=None)
Decorator to define a custom error handler for SocketIO events.
This decorator can be applied to a function that acts as an error handler for a namespace.
This handler will be invoked when a SocketIO event handler raises an exception. The han-
dler function must accept one argument, which is the exception raised. Example:
@socketio.on_error(namespace='/chat')
def chat_error_handler(e):
print('An error has occurred: ' + str(e))
Parameters: namespace – The namespace for which to register the error handler.
Defaults to the global namespace.
on_error_default(exception_handler)
Decorator to define a default error handler for SocketIO events.
This decorator can be applied to a function that acts as a default error handler for any
namespaces that do not have a specific handler. Example:
@socketio.on_error_default
def error_handler(e):
print('An error has occurred: ' + str(e))
Example:
def on_foo_event(json):
print('received json: ' + str(json))
Parameters: message – The name of the event. This is normally a user defined string,
but a few event names are already defined. Use 'message' to define a
handler that takes a string payload, 'json' to define a handler that takes
a JSON blob payload, 'connect' or 'disconnect' to create handlers for
connection and disconnection events.
handler – The function that handles the event.
namespace – The namespace on which the handler is to be registered.
Defaults to the global namespace.
event(*args, **kwargs)
Decorator to register an event handler.
This is a simplified version of the on() method that takes the event name from the deco-
rated function.
Example usage:
@socketio.event
def my_event(data):
print('Received data: ', data)
@socketio.on('my_event')
def my_event(data):
print('Received data: ', data)
@socketio.event(namespace='/test')
def my_event(data):
print('Received data: ', data)
This function emits a SocketIO event to one or more connected clients. A JSON blob can be
attached to the event as payload. This function can be used outside of a SocketIO event con-
text, so it is appropriate to use when the server is the originator of an event, outside of any
client context, such as in a regular HTTP request handler or a background task. Example:
@app.route('/ping')
def ping():
socketio.emit('ping event', {'data': 42}, namespace='/chat')
This method issues an emit with a callback and waits for the callback to be invoked by the
client before returning. If the callback isn’t invoked before the timeout, then a
TimeoutError exception is raised. If the Socket.IO connection drops during the wait, this
method still waits until the specified timeout. Example:
def get_status(client, data):
status = call('status', {'data': data}, to=client)
This function sends a simple SocketIO message to one or more connected clients. The mes-
sage can be a string or a JSON blob. This is a simpler version of emit(), which should be
preferred. This function can be used outside of a SocketIO event context, so it is appropri-
ate to use when the server is the originator of an event.
close_room(room, namespace=None)
Close a room.
This function removes any users that are in the given room and then deletes the room from
the server. This function can be used outside of a SocketIO event context.
stop()
Stop a running SocketIO web server.
This is a utility function that applications can use to start a background task using the
method that is compatible with the selected async mode.
This function returns an object that represents the background task, on which the join()
method can be invoked to wait for the task to complete.
sleep(seconds=0)
Sleep for the requested amount of time using the appropriate async model.
This is a utility function that applications can use to put a task to sleep without having to
worry about using the correct call for the selected async mode.
This function emits a SocketIO event to one or more connected clients. A JSON blob can be at-
tached to the event as payload. This is a function that can only be called from a SocketIO event
handler, as in obtains some information from the current client context. Example:
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', {'data': 42})
flask_socketio.send(message, **kwargs)
Send a SocketIO message.
This function sends a simple SocketIO message to one or more connected clients. The message
can be a string or a JSON blob. This is a simpler version of emit(), which should be preferred.
This is a function that can only be called from a SocketIO event handler.
This function puts the user in a room, under the current namespace. The user and the name-
space are obtained from the event context. This is a function that can only be called from a
SocketIO event handler. Example:
@socketio.on('join')
def on_join(data):
username = session['username']
room = data['room']
join_room(room)
send(username + ' has entered the room.', to=room)
This function removes the user from a room, under the current namespace. The user and the
namespace are obtained from the event context. Example:
@socketio.on('leave')
def on_leave(data):
username = session['username']
room = data['room']
leave_room(room)
send(username + ' has left the room.', to=room)
flask_socketio.close_room(room, namespace=None)
Close a room.
This function removes any users that are in the given room and then deletes the room from
the server.
flask_socketio.rooms(sid=None, namespace=None)
Return a list of the rooms the client is in.
This function returns all the rooms the client has entered, including its own room, assigned by
the Socket.IO server.
Parameters: sid – The session id of the client. If not provided, the client is obtained from
the request context.
namespace – The namespace for the room. If not provided, the namespace is
obtained from the request context.
This function terminates the connection with the client. As a result of this call the client will re-
ceive a disconnect event. Example:
@socketio.on('message')
def receive_message(msg):
if is_banned(session['username']):
disconnect()
else:
# ...
Parameters: sid – The session id of the client. If not provided, the client is obtained from
the request context.
namespace – The namespace for the room. If not provided, the namespace is
obtained from the request context.
silent – this option is deprecated.
class flask_socketio.Namespace(namespace=None)
trigger_event(event, *args)
Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses, as it performs the
routing of events to methods. However, this method can be overridden if special dispatch-
ing rules are needed, or if having a single method that catches all events is desired.
close_room(room, namespace=None)
Close a room.
is_connected(namespace=None)
Check if a namespace is connected.
Parameters: namespace – The namespace for the client. If not provided, the client
connects to the server on the global namespace.
query_string – A string with custom query string arguments.
headers – A dictionary with custom HTTP headers.
auth – Optional authentication data, given as a dictionary.
Note that it is usually not necessary to explicitly call this method, since a connection is au-
tomatically established when an instance of this class is created. An example where it this
method would be useful is when the application accepts multiple namespace connections.
disconnect(namespace=None)
Disconnect the client.
get_received(namespace=None)
Return the list of messages received from the server.
Since this is not a real client, any time the server emits an event, the event is simply stored.
The test code can invoke this method to obtain the list of events that were received since
the last call.
Parameters: namespace – The namespace to get events from. The global namespace is
assumed if this argument is not provided.