API reference

Functions

async picows.ws_connect(ws_listener_factory: Callable[[], WSListener], url: str, *, ssl_context: bool | SSLContext | None = None, disconnect_on_exception: bool = True, logger_name: str = 'client', websocket_handshake_timeout=5, **kwargs) Tuple[WSTransport, WSListener]

Open a websocket connection to a given URL.

This function forwards its kwargs directly to asyncio.loop.create_connection

Parameters:
  • ws_listener_factory – A parameterless factory function that returns a user handler. User handler has to derive from WSListener.

  • url – Destination URL

  • ssl_context – optional SSLContext to override default one when wss scheme is used

  • disconnect_on_exception – Indicates whether the client should initiate disconnect on any exception thrown from WSListener.on_ws_frame callbacks

  • logger_name – picows will use picows.<logger_name> logger to do all the logging.

Returns:

WSTransport object and a user handler returned by `ws_listener_factory()’

async picows.ws_create_server(ws_listener_factory: Callable[[WSUpgradeRequest], WSListener | None], host=None, port=None, *, disconnect_on_exception: bool = True, websocket_handshake_timeout=5, logger_name: str = 'server', **kwargs) Server

Create a websocket server listening on TCP port of the host address. This function forwards its kwargs directly to asyncio.loop.create_server

It has a few extra parameters to control the behaviour of websocket

Parameters:
  • ws_listener_factory

    A factory function that accepts a WSUpgradeRequest object and returns a user handler or None.

    The user handler must derive from WSListener and is responsible for processing incoming data.

    If None is returned, then a 404 Not Found page will be sent as a response to the upgrade request, and the client will be disconnected.

    The factory function works as a router. WSUpgradeRequest contains the requested path and headers. Different user listeners may be returned depending on the path and other conditions.

  • host – The host parameter can be set to several types which determine where the server would be listening: * If host is a string, the TCP server is bound to a single network interface specified by host. * If host is a sequence of strings, the TCP server is bound to all network interfaces specified by the sequence. * If host is an empty string or None, all interfaces are assumed and a list of multiple sockets will be returned (most likely one for IPv4 and another one for IPv6).

  • port – specify which port the server should listen on. If 0 or None (the default), a random unused port will be selected (note that if host resolves to multiple network interfaces, a different random port will be selected for each interface).

  • disconnect_on_exception – Indicates whether the client should initiate disconnect on any exception thrown by WSListener.on_ws_frame callback

  • websocket_handshake_timeout – is the time in seconds to wait for the websocket server to receive websocket handshake request before aborting the connection.

  • logger_name – picows will use picows.<logger_name> logger to do all the logging.

Returns:

asyncio.Server object

Classes

class picows.WSError

Exception type for picows library

class picows.WSFrame

Received websocket frame.

Internally WSFrame just points to a chunk of memory in the receiving buffer without copying or owning memory.

Danger

Only use WSFrame object during WSListener.on_ws_frame callback. WSFrame objects are essentially just pointers to the underlying receiving buffer. After WSListener.on_ws_frame has completed the buffer will be reused for the new incoming data.

In order to actually copy payload use one of the get_* methods.

msg_type: WSMsgType

Message type

fin: bool

Indicates whether this is the last frame of the message. Websocket messages MAY consist of multiple frames.

Unfragmented message:

WSFrame(msg_type=WSMsgType.<actual message type>, fin=True)

Fragmented message:

WSFrame(msg_type=WSMsgType.<actual message type>, fin=False)
WSFrame(msg_type=WSMsgType.CONTINUATION, fin=False)
...
# the last frame of the message
WSFrame(msg_type=WSMsgType.CONTINUATION, fin=True)
last_in_buffer: bool

Indicates whether this is the last available frame in the receiving buffer. The receiving buffer may contain more available data, but not the full frame yet.

tail_size: int

Indicates how many bytes are in the receiving buffer after the current frame.

payload_ptr: char*

Available only from Cython.

Raw pointer to the beginning of the frame payload in the receiving buffer.

payload_size: size_t

Available only from Cython.

Size of the payload.

get_close_code()
Returns:

WSCloseCode

This method is only valid for WSMsgType.CLOSE frames.

get_close_message()
Returns:

a new bytes object with a close message. If there is no close message then returns None.

This method is only valid for WSMsgType.CLOSE frames.

get_payload_as_ascii_text()
Returns:

a new str object with a copy of frame payload.

This method will throw if payload does not contain valid ASCII 7 text.

This method does not cache results. Payload is copied and a new str object is created every time this method is called.

get_payload_as_bytes()
Returns:

a new bytes object with a copy of frame payload.

This method does not cache results. Payload is copied and a new bytes object is created every time this method is called.

get_payload_as_memoryview()
Returns:

continous memoryview to a parser buffer with payload.

Danger

Returned memoryview does NOT own the underlying memory. The content will be invalidated after WSListener.on_ws_frame has completed. Please process payload or copy it as soon as possible.

get_payload_as_utf8_text()
Returns:

a new str object with a copy of frame payload.

This method will throw if payload does not contain valid UTF8 text.

This method does not cache results. Payload is copied and a new str object is created every time this method is called.

class picows.WSUpgradeRequest
method: bytes

Request method. b”GET”, b”POST”, etc

path: bytes

Request path. For example b”/ws”

version: bytes

HTTP version. For example b”HTTP/1.1”

headers: Dict[str, str]

Request headers. header names are always in lowercase

class picows.WSListener

Base class for user handlers.

All on_ws_* methods receive transport as a first argument for convenience. It is guaranteed that passed transport object is always the same for the same connection.

on_ws_connected(transport)

Called after websocket handshake is complete and websocket is ready to send and receive frames. Initiate disconnect if exception is thrown by user handler.

Parameters:

transportWSTransport object

on_ws_disconnected(transport)

Called when websocket has been disconnected.

Parameters:

transportWSTransport

on_ws_frame(transport, frame)

Called when a new frame is received.

Initiate disconnect if exception is thrown by user handler and disconnect_on_exception was set to True in ws_connect or ws_create_server

Danger

WSFrame is essentially just a pointer to a chunk of memory in the receiving buffer. It does not own the memory. Do NOT cache or store WSFrame object for later processing because the data may be invalidated after WSListener.on_ws_frame is complete. Process the payload immediatelly or just copy it with one of WSFrame.get_* methods.

Parameters:
pause_writing()

Called when the underlying transport’s buffer goes over the high watermark.

resume_writing()

Called when the underlying transport’s buffer drains below the low watermark.

class picows.WSTransport
underlying_transport: asyncio.Transport

Underlying TCP or SSL transport. Can be used to set buffer limits, check connection state, etc.

Please don’t use it to send data. Use only WSTransport.send_* methods to send frames.

send_reuse_external_buffer(WSMsgType msg_type, char* message, size_t message_size)
Parameters:
  • msg_type – Message type

  • message – Pointer to a message payload

  • message_size – Size of the message payload

Available only from Cython.

Send a frame over websocket with a message as its payload. Don’t copy message, reuse its memory and append websocket header in front of the message

Message’s buffer should have at least 10 bytes in front of the message pointer available for writing.

disconnect()

Close the underlying transport.

If there is unsent outgoing data in the buffer, it will be flushed asynchronously. No more data will be received. It is ok to call this method multiple times. It does nothing if the transport is already closed.

send(msg_type, message, rsv1=False)

Send a frame over websocket with a message as its payload.

Parameters:
  • msg_typeWSMsgType enum value

  • message – an optional bytes-like object

  • rsv1 – first reserved bit in websocket frame.

Some protocol extensions use it to indicate that the payload is compressed.

send_close(close_code=<WSCloseCode.NO_INFO: 0>, close_message=None)

Send a CLOSE control frame with an optional message. This method doesn’t disconnect the underlying transport. Does nothing if the underlying transport is already disconnected.

Parameters:
  • close_codeWSCloseCode value

  • close_message – an optional bytes-like object

send_ping(message=None)

Send a PING control frame with an optional message.

Parameters:

message – an optional bytes-like object

send_pong(message=None)

Send a PONG control frame with an optional message.

Parameters:

message – an optional bytes-like object

async wait_disconnected()

Coroutine that conveniently allows to wait until websocket is completely disconnected. (underlying transport is closed, on_ws_disconnected has been called)

Enums

enum picows.WSMsgType(value)
Member Type:

int

Valid values are as follows:

CONTINUATION = <WSMsgType.CONTINUATION: 0>
TEXT = <WSMsgType.TEXT: 1>
BINARY = <WSMsgType.BINARY: 2>
PING = <WSMsgType.PING: 9>
PONG = <WSMsgType.PONG: 10>
CLOSE = <WSMsgType.CLOSE: 8>
enum picows.WSCloseCode(value)
Member Type:

int

Valid values are as follows:

NO_INFO = <WSCloseCode.NO_INFO: 0>
OK = <WSCloseCode.OK: 1000>
GOING_AWAY = <WSCloseCode.GOING_AWAY: 1001>
PROTOCOL_ERROR = <WSCloseCode.PROTOCOL_ERROR: 1002>
UNSUPPORTED_DATA = <WSCloseCode.UNSUPPORTED_DATA: 1003>
ABNORMAL_CLOSURE = <WSCloseCode.ABNORMAL_CLOSURE: 1006>
INVALID_TEXT = <WSCloseCode.INVALID_TEXT: 1007>
POLICY_VIOLATION = <WSCloseCode.POLICY_VIOLATION: 1008>
MESSAGE_TOO_BIG = <WSCloseCode.MESSAGE_TOO_BIG: 1009>
MANDATORY_EXTENSION = <WSCloseCode.MANDATORY_EXTENSION: 1010>
INTERNAL_ERROR = <WSCloseCode.INTERNAL_ERROR: 1011>
SERVICE_RESTART = <WSCloseCode.SERVICE_RESTART: 1012>
TRY_AGAIN_LATER = <WSCloseCode.TRY_AGAIN_LATER: 1013>
BAD_GATEWAY = <WSCloseCode.BAD_GATEWAY: 1014>