Python - websocket.on()

Register a handler for a specific websocket event.

from nitric.resources import websocket
from nitric.application import Nitric
chat_websocket = websocket("chat")
@chat_websocket.on("connect")
async def on_connect(ctx):
print("connecting ", ctx.req.connection_id)
ctx.res.success = true
Nitric.run()

Parameters

  • Name
    event_type
    Required
    Required
    Type
    string
    Description

    The event to respond to on the websocket, valid values are 'connect', 'disconnect' and 'message'.

All event types (connect, disconnect and message) must be handled, or the project will not be valid for deployment.

Examples

Websocket example with all available event types

from nitric.resources import websocket
from nitric.application import Nitric
public_websocket = websocket("public")
@public_websocket.on("connect")
async def on_connect(ctx):
print("connecting ", ctx.req.connection_id)
ctx.res.success = true
@public_websocket.on("disconnect")
async def on_disconnect(ctx):
print("disconnecting ", ctx.req.connection_id)
ctx.res.success = true
@public_websocket.on("message")
async def on_message(ctx):
print("handling message from ", ctx.req.connection_id)
ctx.res.success = true
Nitric.run()
Last updated on Nov 4, 2024