API Reference

class flask_socketio.SocketIO(app=None, **kwargs)

Create a Flask-SocketIO server.

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 setting 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 processes 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.

The Socket.IO server options are detailed below:

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 argument does not need to be set explicitly.
  • logger – To enable 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 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 compatible with the standard library versions. To use the same json encoder and decoder 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 confused when it receives events before the connection acceptance. In any other case use the default of False.

The Engine.IO server configuration supports the following settings:

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 respond 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 arguments, 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 allowed 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 recommended). 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.
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.

Parameters:
  • room – The name of the room to close.
  • namespace – The namespace under which the room exists. Defaults to the global namespace.
emit(event, *args, **kwargs)

Emit a server generated SocketIO event.

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 context, 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')
Parameters:
  • event – The name of the user event to emit.
  • args – A dictionary with the JSON data to send as payload.
  • namespace – The namespace under which the message is to be sent. Defaults to the global namespace.
  • to – Send the message to all the users in the given room. If this parameter is not included, the event is sent to all connected users.
  • include_selfTrue to include the sender when broadcasting or addressing a room, or False to send to everyone but the sender.
  • skip_sid – The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list.
  • callback – If given, this function will be called to acknowledge that the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client.
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 decorated function.

Example usage:

@socketio.event
def my_event(data):
    print('Received data: ', data)

The above example is equivalent to:

@socketio.on('my_event')
def my_event(data):
    print('Received data: ', data)

A custom namespace can be given as an argument to the decorator:

@socketio.event(namespace='/test')
def my_event(data):
    print('Received data: ', data)
on(message, namespace=None)

Decorator to register a SocketIO event handler.

This decorator must be applied to SocketIO event handlers. Example:

@socketio.on('my event', namespace='/chat')
def handle_my_custom_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.
  • 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 handler 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))
on_event(message, handler, namespace=None)

Register a SocketIO event handler.

on_event is the non-decorator version of 'on'.

Example:

def on_foo_event(json):
    print('received json: ' + str(json))

socketio.on_event('my event', on_foo_event, namespace='/chat')
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.
run(app, host=None, port=None, **kwargs)

Run the SocketIO web server.

Parameters:
  • app – The Flask application instance.
  • host – The hostname or IP address for the server to listen on. Defaults to 127.0.0.1.
  • port – The port number for the server to listen on. Defaults to 5000.
  • debugTrue to start the server in debug mode, False to start in normal mode.
  • use_reloaderTrue to enable the Flask reloader, False to disable it.
  • reloader_options – A dictionary with options that are passed to the Flask reloader, such as extra_files, reloader_type, etc.
  • extra_files – A list of additional files that the Flask reloader should watch. Defaults to None. Deprecated, use reloader_options instead.
  • log_output – If True, the server logs all incoming connections. If False logging is disabled. Defaults to True in debug mode, False in normal mode. Unused when the threading async mode is used.
  • kwargs – Additional web server options. The web server options are specific to the server used in each of the supported async modes. Note that options provided here will not be seen when using an external web server such as gunicorn, since this method is not called in that case.
send(data, json=False, namespace=None, to=None, callback=None, include_self=True, skip_sid=None, **kwargs)

Send a server-generated 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 function can be used outside of a SocketIO event context, so it is appropriate to use when the server is the originator of an event.

Parameters:
  • data – The message to send, either a string or a JSON blob.
  • jsonTrue if message is a JSON blob, False otherwise.
  • namespace – The namespace under which the message is to be sent. Defaults to the global namespace.
  • to – Send the message only to the users in the given room. If this parameter is not included, the message is sent to all connected users.
  • include_selfTrue to include the sender when broadcasting or addressing a room, or False to send to everyone but the sender.
  • skip_sid – The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list.
  • callback – If given, this function will be called to acknowledge that the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client.
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.

start_background_task(target, *args, **kwargs)

Start a background task using the appropriate async model.

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.

Parameters:
  • target – the target function to execute.
  • args – arguments to pass to the function.
  • kwargs – keyword arguments to pass to the function.

This function returns an object compatible with the Thread class in the Python standard library. The start() method on this object is already called by this function.

stop()

Stop a running SocketIO web server.

This method must be called from a HTTP or SocketIO handler function.

test_client(app, namespace=None, query_string=None, headers=None, auth=None, flask_test_client=None)

The Socket.IO test client is useful for testing a Flask-SocketIO server. It works in a similar way to the Flask Test Client, but adapted to the Socket.IO server.

Parameters:
  • app – The Flask application instance.
  • 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.
  • flask_test_client – The instance of the Flask test client currently in use. Passing the Flask test client is optional, but is necessary if you want the Flask user session and any other cookies set in HTTP routes accessible from Socket.IO events.
flask_socketio.emit(event, *args, **kwargs)

Emit a SocketIO event.

This function emits a SocketIO event to one or more connected clients. A JSON blob can be attached 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})
Parameters:
  • event – The name of the user event to emit.
  • args – A dictionary with the JSON data to send as payload.
  • namespace – The namespace under which the message is to be sent. Defaults to the namespace used by the originating event. A '/' can be used to explicitly specify the global namespace.
  • callback – Callback function to invoke with the client’s acknowledgement.
  • broadcastTrue to send the message to all clients, or False to only reply to the sender of the originating event.
  • to – Send the message to all the users in the given room. If this argument is not set and broadcast is False, then the message is sent only to the originating user.
  • include_selfTrue to include the sender when broadcasting or addressing a room, or False to send to everyone but the sender.
  • skip_sid – The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list.
  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used, or when there is a single addressee. It is recommended to always leave this parameter with its default value of False.
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.

Parameters:
  • message – The message to send, either a string or a JSON blob.
  • jsonTrue if message is a JSON blob, False otherwise.
  • namespace – The namespace under which the message is to be sent. Defaults to the namespace used by the originating event. An empty string can be used to use the global namespace.
  • callback – Callback function to invoke with the client’s acknowledgement.
  • broadcastTrue to send the message to all connected clients, or False to only reply to the sender of the originating event.
  • to – Send the message to all the users in the given room. If this argument is not set and broadcast is False, then the message is sent only to the originating user.
  • include_selfTrue to include the sender when broadcasting or addressing a room, or False to send to everyone but the sender.
  • skip_sid – The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list.
  • ignore_queue – Only used when a message queue is configured. If set to True, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used, or when there is a single addressee. It is recommended to always leave this parameter with its default value of False.
flask_socketio.join_room(room, sid=None, namespace=None)

Join a room.

This function puts the user in a room, under the current namespace. The user and the namespace 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)
Parameters:
  • room – The name of the room to join.
  • 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.
flask_socketio.leave_room(room, sid=None, namespace=None)

Leave a 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)
Parameters:
  • room – The name of the room to leave.
  • 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.
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.

Parameters:
  • room – The name of the room to close.
  • namespace – The namespace for the room. If not provided, the namespace is obtained from the request context.
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.
flask_socketio.disconnect(sid=None, namespace=None, silent=False)

Disconnect the client.

This function terminates the connection with the client. As a result of this call the client will receive 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)
close_room(room, namespace=None)

Close a room.

emit(event, data=None, room=None, include_self=True, namespace=None, callback=None)

Emit a custom event to one or more connected clients.

send(data, room=None, include_self=True, namespace=None, callback=None)

Send a message to one or more connected clients.

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 dispatching rules are needed, or if having a single method that catches all events is desired.

class flask_socketio.SocketIOTestClient(app, socketio, namespace=None, query_string=None, headers=None, auth=None, flask_test_client=None)

This class is useful for testing a Flask-SocketIO server. It works in a similar way to the Flask Test Client, but adapted to the Socket.IO server.

Parameters:
  • app – The Flask application instance.
  • socketio – The application’s SocketIO instance.
  • 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.
  • flask_test_client – The instance of the Flask test client currently in use. Passing the Flask test client is optional, but is necessary if you want the Flask user session and any other cookies set in HTTP routes accessible from Socket.IO events.
connect(namespace=None, query_string=None, headers=None, auth=None)

Connect the client.

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 automatically 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.

Parameters:namespace – The namespace to disconnect. The global namespace is assumed if this argument is not provided.
emit(event, *args, **kwargs)

Emit an event to the server.

Parameters:
  • event – The event name.
  • *args

    The event arguments.

  • callbackTrue if the client requests a callback, False if not. Note that client-side callbacks are not implemented, a callback request will just tell the server to provide the arguments to invoke the callback, but no callback is invoked. Instead, the arguments that the server provided for the callback are returned by this function.
  • namespace – The namespace of the event. The global namespace is assumed if this argument is not provided.
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.
is_connected(namespace=None)

Check if a namespace is connected.

Parameters:namespace – The namespace to check. The global namespace is assumed if this argument is not provided.
send(data, json=False, callback=False, namespace=None)

Send a text or JSON message to the server.

Parameters:
  • data – A string, dictionary or list to send to the server.
  • jsonTrue to send a JSON message, False to send a text message.
  • callbackTrue if the client requests a callback, False if not. Note that client-side callbacks are not implemented, a callback request will just tell the server to provide the arguments to invoke the callback, but no callback is invoked. Instead, the arguments that the server provided for the callback are returned by this function.
  • namespace – The namespace of the event. The global namespace is assumed if this argument is not provided.