API Reference¶
- classflask_socketio.SocketIO(app=None,**kwargs)¶
Create a Flask-SocketIO server.
- Parameters:
app – The flask application instance. If the application instanceisn’t known at the time this class is instantiated, then call
socketio.init_app(app)
once the application instance isavailable.manage_session – If set to
True
, this extension manages the usersession for Socket.IO events. If set toFalse
,Flask’s own session management is used. When usingFlask’s cookie based sessions it is recommended thatyou leave this set to the default ofTrue
. Whenusing server-side sessions, aFalse
settingenables sharing the user session between HTTP routesand Socket.IO events.message_queue – A connection URL for a message queue service theserver can use for multi-process communication. Amessage queue is not required when using a singleserver process.
channel – The channel name, when using a message queue. If a channelisn’t specified, a default channel will be used. Ifmultiple clusters of SocketIO processes need to use thesame 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 aredoing.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 theclient list. When this is omitted, the client listis stored in an in-memory structure, so the use ofmultiple connected servers is not possible. In mostcases, this argument does not need to be setexplicitly.
logger – To enable logging set to
True
or pass a logger object touse. To disable logging set toFalse
. The default isFalse
. Note that fatal errors will be logged even whenlogger
isFalse
.json – An alternative json module to use for encoding and decodingpackets. Custom json modules must have
dumps
andloads
functions that are compatible with the standard libraryversions. To use the same json encoder and decoder as a Flaskapplication, useflask.json
.async_handlers – If set to
True
, event handlers for a client areexecuted in separate threads. To run handlers for aclient synchronously, set toFalse
. The defaultisTrue
.always_connect – When set to
False
, new connections areprovisory until the connect handler returnssomething other thanFalse
, at which point theyare accepted. When set toTrue
, connections areimmediately accepted, and then if the connecthandler returnsFalse
a disconnect is issued.Set toTrue
if you need to emit events from theconnect handler and your client is confused when itreceives events before the connection acceptance.In any other case use the default ofFalse
.
The Engine.IO server configuration supports the following settings:
- Parameters:
async_mode – The asynchronous model to use. See the Deploymentsection in the documentation for a description of theavailable options. Valid async modes are
threading
,eventlet
,gevent
andgevent_uwsgi
. If thisargument is not given,eventlet
is tried first, thengevent_uwsgi
, thengevent
, and finallythreading
. The first async mode that has all itsdependencies installed is then one that is chosen.ping_interval – The interval in seconds at which the server pingsthe client. The default is 25 seconds. For advancedcontrol, a two element tuple can be given, wherethe first number is the ping interval and the secondis a grace period added by the server.
ping_timeout – The time in seconds that the client waits for theserver to respond before disconnecting. The defaultis 5 seconds.
max_http_buffer_size – The maximum size of a message when using thepolling transport. The default is 1,000,000bytes.
allow_upgrades – Whether to allow transport upgrades or not. Thedefault is
True
.http_compression – Whether to compress packages when using thepolling transport. The default is
True
.compression_threshold – Only compress messages when their byte sizeis greater than this value. The default is1024 bytes.
cookie – If set to a string, it is the name of the HTTP cookie theserver sends back to the client containing the clientsession id. If set to a dictionary, the
'name'
keycontains the cookie name and other keys define cookieattributes, where the value of each attribute can be astring, a callable with no arguments, or a boolean. If settoNone
(the default), a cookie is not sent to theclient.cors_allowed_origins – Origin or list of origins that are allowed toconnect to this server. Only the same originis allowed by default. Set this argument to
'*'
to allow all origins, or to[]
todisable CORS handling.cors_credentials – Whether credentials (cookies, authentication) areallowed in requests to this server. The default is
True
.monitor_clients – If set to
True
, a background task will ensureinactive clients are closed. Set toFalse
todisable the monitoring task (not recommended). Thedefault isTrue
.engineio_logger – To enable Engine.IO logging set to
True
or passa logger object to use. To disable logging set toFalse
. The default isFalse
. Note thatfatal errors are logged even whenengineio_logger
isFalse
.
- classreason¶
Disconnection reasons.
- CLIENT_DISCONNECT='clientdisconnect'¶
Client-initiated disconnection.
- PING_TIMEOUT='pingtimeout'¶
Ping timeout.
- SERVER_DISCONNECT='serverdisconnect'¶
Server-initiated disconnection.
- TRANSPORT_CLOSE='transportclose'¶
Transport close.
- TRANSPORT_ERROR='transporterror'¶
Transport error.
- 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')defhandle_my_custom_event(json):print('received json: '+str(json))
- Parameters:
message – The name of the event. This is normally a user definedstring, but a few event names are already defined. Use
'message'
to define a handler that takes a stringpayload,'json'
to define a handler that takes aJSON blob payload,'connect'
or'disconnect'
to create handlers for connection and disconnectionevents.namespace – The namespace on which the handler is to beregistered. 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 errorhandler for a namespace. This handler will be invoked when a SocketIOevent handler raises an exception. The handler function must accept oneargument, which is the exception raised. Example:
@socketio.on_error(namespace='/chat')defchat_error_handler(e):print('An error has occurred: '+str(e))
- Parameters:
namespace – The namespace for which to register the errorhandler. 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 defaulterror handler for any namespaces that do not have a specific handler.Example:
@socketio.on_error_defaultdeferror_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:
defon_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 definedstring, but a few event names are already defined. Use
'message'
to define a handler that takes a stringpayload,'json'
to define a handler that takes aJSON blob payload,'connect'
or'disconnect'
to create handlers for connection and disconnectionevents.handler – The function that handles the event.
namespace – The namespace on which the handler is to beregistered. 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 theevent name from the decorated function.Example usage:
@socketio.eventdefmy_event(data):print('Received data: ',data)
The above example is equivalent to:
@socketio.on('my_event')defmy_event(data):print('Received data: ',data)
A custom namespace can be given as an argument to the decorator:
@socketio.event(namespace='/test')defmy_event(data):print('Received data: ',data)
- 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 canbe used outside of a SocketIO event context, so it is appropriate touse when the server is the originator of an event, outside of anyclient context, such as in a regular HTTP request handler or abackground task. Example:
@app.route('/ping')defping():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, or tothe user with the given session ID. If this parameter is notincluded, the event is sent to all connected users.
include_self –
True
to include the sender when broadcastingor addressing a room, orFalse
to send toeveryone but the sender.skip_sid – The session id of a client to ignore when broadcastingor addressing a room. This is typically set to theoriginator of the message, so that everyone exceptthat client receive the message. To skip multiple sidspass a list.
callback – If given, this function will be called to acknowledgethat the client has received the message. Thearguments that will be passed to the function arethose provided by the client. Callback functions canonly be used when addressing an individual client.
- call(event,*args,**kwargs)¶
Emit a SocketIO event and wait for the response.
This method issues an emit with a callback and waits for the callbackto be invoked by the client before returning. If the callback isn’tinvoked before the timeout, then a TimeoutError exception is raised. Ifthe Socket.IO connection drops during the wait, this method still waitsuntil the specified timeout. Example:
defget_status(client,data):status=call('status',{'data':data},to=client)
- 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 – The session ID of the recipient client.
timeout – The waiting timeout. If the timeout is reached beforethe client acknowledges the event, then a
TimeoutError
exception is raised. The default is 60seconds.ignore_queue – Only used when a message queue is configured. Ifset to
True
, the event is emitted to theclient directly, without going through the queue.This is more efficient, but only works when asingle server process is used, or when there is asingle addressee. It is recommended to alwaysleave this parameter with its default value ofFalse
.
- 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 connectedclients. The message can be a string or a JSON blob. This is a simplerversion of
emit()
, which should be preferred. This function can beused outside of a SocketIO event context, so it is appropriate to usewhen the server is the originator of an event.- Parameters:
data – The message to send, either a string or a JSON blob.
json –
True
ifmessage
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 to all the users in the given room, or tothe user with the given session ID. If this parameter is notincluded, the event is sent to all connected users.
include_self –
True
to include the sender when broadcastingor addressing a room, orFalse
to send toeveryone but the sender.skip_sid – The session id of a client to ignore when broadcastingor addressing a room. This is typically set to theoriginator of the message, so that everyone exceptthat client receive the message. To skip multiple sidspass a list.
callback – If given, this function will be called to acknowledgethat the client has received the message. Thearguments that will be passed to the function arethose provided by the client. Callback functions canonly be used when addressing an individual client.
- close_room(room,namespace=None)¶
Close a room.
This function removes any users that are in the given room and thendeletes the room from the server. This function can be used outsideof a SocketIO event context.
- Parameters:
room – The name of the room to close.
namespace – The namespace under which the room exists. Defaultsto 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 to5000.
debug –
True
to start the server in debug mode,False
tostart in normal mode.use_reloader –
True
to enable the Flask reloader,False
to disable it.reloader_options – A dictionary with options that are passed tothe Flask reloader, such as
extra_files
,reloader_type
, etc.extra_files – A list of additional files that the Flaskreloader should watch. Defaults to
None
.Deprecated, usereloader_options
instead.log_output – If
True
, the server logs all incomingconnections. IfFalse
logging is disabled.Defaults toTrue
in debug mode,False
in normal mode. Unused when the threading asyncmode is used.allow_unsafe_werkzeug – Set to
True
to allow the use of theWerkzeug web server in a productionsetting. Default isFalse
. Set toTrue
at your own risk.kwargs – Additional web server options. The web server optionsare specific to the server used in each of the supportedasync modes. Note that options provided here willnot be seen when using an external web server suchas gunicorn, since this method is not called in thatcase.
- stop()¶
Stop a running SocketIO web server.
This method must be called from a HTTP or SocketIO handler function.
- 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 abackground task using the method that is compatible with theselected 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 that represents the background task,on which the
join()
method can be invoked to wait for the task tocomplete.
- sleep(seconds=0)¶
Sleep for the requested amount of time using the appropriate asyncmodel.
This is a utility function that applications can use to put a task tosleep without having to worry about using the correct call for theselected async mode.
- 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-SocketIOserver. It works in a similar way to the Flask Test Client, butadapted to the Socket.IO server.
- Parameters:
app – The Flask application instance.
namespace – The namespace for the client. If not provided, theclient connects to the server on the globalnamespace.
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 clientcurrently in use. Passing the Flask testclient is optional, but is necessary if youwant the Flask user session and any othercookies set in HTTP routes accessible fromSocket.IO events.
- flask_socketio.emit(event,*args,**kwargs)¶
Emit a SocketIO event.
This function emits a SocketIO event to one or more connected clients. AJSON blob can be attached to the event as payload. This is a function thatcan only be called from a SocketIO event handler, as in obtains someinformation from the current client context. Example:
@socketio.on('my event')defhandle_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 globalnamespace.callback – Callback function to invoke with the client’sacknowledgement.
broadcast –
True
to send the message to all clients, orFalse
to only reply to the sender of the originating event.to – Send the message to all the users in the given room, or to theuser with the given session ID. If this argument is not set and
broadcast
isFalse
, then the message is sent only to theoriginating user.include_self –
True
to include the sender when broadcasting oraddressing a room, orFalse
to send to everyonebut the sender.skip_sid – The session id of a client to ignore when broadcastingor addressing a room. This is typically set to theoriginator of the message, so that everyone exceptthat client receive the message. To skip multiple sidspass a list.
ignore_queue – Only used when a message queue is configured. Ifset to
True
, the event is emitted to theclients directly, without going through the queue.This is more efficient, but only works when asingle server process is used, or when there is asingle addressee. It is recommended to always leavethis parameter with its default value ofFalse
.
- flask_socketio.send(message,**kwargs)¶
Send a SocketIO message.
This function sends a simple SocketIO message to one or more connectedclients. The message can be a string or a JSON blob. This is a simplerversion of
emit()
, which should be preferred. This is a function thatcan only be called from a SocketIO event handler.- Parameters:
message – The message to send, either a string or a JSON blob.
json –
True
ifmessage
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’sacknowledgement.
broadcast –
True
to send the message to all connected clients, orFalse
to only reply to the sender of the originatingevent.to – Send the message to all the users in the given room, or to theuser with the given session ID. If this argument is not set and
broadcast
isFalse
, then the message is sent only to theoriginating user.include_self –
True
to include the sender when broadcasting oraddressing a room, orFalse
to send to everyonebut the sender.skip_sid – The session id of a client to ignore when broadcastingor addressing a room. This is typically set to theoriginator of the message, so that everyone exceptthat client receive the message. To skip multiple sidspass a list.
ignore_queue – Only used when a message queue is configured. Ifset to
True
, the event is emitted to theclients directly, without going through the queue.This is more efficient, but only works when asingle server process is used, or when there is asingle addressee. It is recommended to always leavethis parameter with its default value ofFalse
.
- flask_socketio.join_room(room,sid=None,namespace=None)¶
Join a room.
This function puts the user in a room, under the current namespace. Theuser and the namespace are obtained from the event context. This is afunction that can only be called from a SocketIO event handler. Example:
@socketio.on('join')defon_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 isobtained from the request context.
namespace – The namespace for the room. If not provided, thenamespace 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')defon_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 isobtained from the request context.
namespace – The namespace for the room. If not provided, thenamespace 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 deletesthe room from the server.
- Parameters:
room – The name of the room to close.
namespace – The namespace for the room. If not provided, thenamespace 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 itsown room, assigned by the Socket.IO server.
- Parameters:
sid – The session id of the client. If not provided, the client isobtained from the request context.
namespace – The namespace for the room. If not provided, thenamespace 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 ofthis call the client will receive a disconnect event. Example:
@socketio.on('message')defreceive_message(msg):ifis_banned(session['username']):disconnect()else:# ...
- Parameters:
sid – The session id of the client. If not provided, the client isobtained from the request context.
namespace – The namespace for the room. If not provided, thenamespace is obtained from the request context.
silent – this option is deprecated.
- classflask_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, thismethod can be overridden if special dispatching rules are needed, or ifhaving a single method that catches all events is desired.
- 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.
- close_room(room,namespace=None)¶
Close a room.
- classflask_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 asimilar 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 clientconnects 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 clientcurrently in use. Passing the Flask testclient is optional, but is necessary if youwant the Flask user session and any othercookies set in HTTP routes accessible fromSocket.IO events.
- is_connected(namespace=None)¶
Check if a namespace is connected.
- Parameters:
namespace – The namespace to check. The global namespace isassumed if this argument is not provided.
- connect(namespace=None,query_string=None,headers=None,auth=None)¶
Connect the client.
- Parameters:
namespace – The namespace for the client. If not provided, theclient connects to the server on the globalnamespace.
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 ofthis class is created. An example where it this method would be usefulis when the application accepts multiple namespace connections.
- disconnect(namespace=None)¶
Disconnect the client.
- Parameters:
namespace – The namespace to disconnect. The global namespace isassumed 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.
callback –
True
if the client requests a callback,False
if not. Note that client-side callbacks are notimplemented, a callback request will just tell theserver to provide the arguments to invoke thecallback, but no callback is invoked. Instead, thearguments that the server provided for the callbackare returned by this function.namespace – The namespace of the event. The global namespace isassumed 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.
json –
True
to send a JSON message,False
to send a textmessage.callback –
True
if the client requests a callback,False
if not. Note that client-side callbacks are notimplemented, a callback request will just tell theserver to provide the arguments to invoke thecallback, but no callback is invoked. Instead, thearguments that the server provided for the callbackare returned by this function.namespace – The namespace of the event. The global namespace isassumed 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 toobtain the list of events that were received since the last call.
- Parameters:
namespace – The namespace to get events from. The globalnamespace is assumed if this argument is notprovided.