Mojo.SocketHandlers

Mojo has added some simple convenience to TornadIO2 SocketConnections by adding two key dictionaries to the framework. These dictionaries are populated (and depopulated) as users connect to the site.

The dictionaries that are made available are:

  • CURRENT_SESSIONS: Keyed by the session ID of the user
  • LOGGED_IN_SESSIONS: Keyed by the user ID of the (logged in) user (requires Mojo.Auth to be enabled).

Usage:

from Mojo.SocketHandlers.BaseSocketHandler import MojoSocketHandler, CURRENT_SESSIONS, LOGGED_IN_SESSIONS

#Setup your socket connections here (remember to subclass MojoSocketHandler)
class SocketConnectionHandler(MojoSocketHandler):
    def on_message(self, msg):
        pass
class Mojo.SocketHandlers.BaseSocketHandler.MojoSocketHandler(session, endpoint=None)

The MojoSocketHandler overrides the on_open and on_close events of the standard TornadIO2 SocketConnection to expose some simple session data (self.session_id and self.logged_in).

MojoSocketHandler will store connections in a global dictionary called CURRENT_SESSIONS, all connections are keyed by the user session_id (generated automatically on request).

You can import CURRENT_SESSIONS to broadcast to all users, or emit messages to specific users based on their session_id.

If you are using the Mojo.Auth module, and the cookie logged_in is set (i.e. the user is logged in), then another global dictionary: LOGGED_IN_SESSIONS is populated with the connection, keyed by the user_id of the user. This makes common tasks much simpler to manage such as:

  • Broadcasting to all connected clients
  • Broadcasting to only logged in users
  • Online ‘status’ checking of logged in users - e.g. for chat.
  • Event-based messaging, e.g. with signals
Read the Docs v: latest
Versions
latest
Downloads
PDF
HTML
Epub
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.