WebSocket

exception microdot.websocket.WebSocketError

Exception raised when an error occurs in a WebSocket connection.

class microdot.websocket.WebSocket(request)

A WebSocket connection object.

An instance of this class is sent to handler functions to manage the WebSocket connection.

max_message_length = -1

Specify the maximum message size that can be received when calling the receive() method. Messages with payloads that are larger than this size will be rejected and the connection closed. Set to 0 to disable the size check (be aware of potential security issues if you do this), or to -1 to use the value set in Request.max_body_length. The default is -1.

Example:

WebSocket.max_message_length = 4 * 1024  # up to 4KB messages
async receive()

Receive a message from the client.

async send(data, opcode=None)

Send a message to the client.

Parameters:
  • data – the data to send, given as a string or bytes.

  • opcode – a custom frame opcode to use. If not given, the opcode is TEXT or BINARY depending on the type of the data.

async close()

Close the websocket connection.

async microdot.websocket.websocket_upgrade(request)

Upgrade a request handler to a websocket connection.

This function can be called directly inside a route function to process a WebSocket upgrade handshake, for example after the user’s credentials are verified. The function returns the websocket object:

@app.route('/echo')
async def echo(request):
    if not authenticate_user(request):
        abort(401)
    ws = await websocket_upgrade(request)
    while True:
        message = await ws.receive()
        await ws.send(message)
microdot.websocket.with_websocket(f)

Decorator to make a route a WebSocket endpoint.

This decorator is used to define a route that accepts websocket connections. The route then receives a websocket object as a second argument that it can use to send and receive messages:

@app.route('/echo')
@with_websocket
async def echo(request, ws):
    while True:
        message = await ws.receive()
        await ws.send(message)