Websockets in Gramex

We can use websockets to persist bidirectional connections with server. WebSocketHandler docs.

How can this be useful?

Useful for real-time applications: insights or feed or data extraction, chat bots.

Gramex supports Websockets - YAML

    pattern: /$YAMLURL/ws
    handler: WebSocketHandler
            function: app.ws_open
            function: app.ws_on_message
            function: app.close
        auth: true

Send a request - Javascript

protocols = {http: 'ws://', https: 'wss://'}
ws = new WebSocket(protocols[window.location.protocol] + window.location.hostname + ":" + window.location.port + "/ws")

// this maps to yaml definition of kwargs.open which maps to app.open()
ws.onopen = function() {
  // your code

ws.onmessage = function() {
  // your functionality

ws.onerror = function() {
  // error handling

Requests are served as they are complete. Examples of backend can be found for Autolysis below.

Do we already use it?

Google search [code - client]. Each search result for a keyword/domain combination is fetched over a websocket connection.

Autolysis [code - server]. Each groupmeans cell here is yielded over a websocket connection.