Data structures

WebSocket events

class websockets.frames.Frame(opcode, data, fin=True, rsv1=False, rsv2=False, rsv3=False)

WebSocket frame.

opcode

Opcode.

Type:

websockets.frames.Opcode

data

Payload data.

Type:

bytes | bytearray | memoryview

fin

FIN bit.

Type:

bool

rsv1

RSV1 bit.

Type:

bool

rsv2

RSV2 bit.

Type:

bool

rsv3

RSV3 bit.

Type:

bool

Only these fields are needed. The MASK bit, payload length and masking-key are handled on the fly when parsing and serializing frames.

class websockets.frames.Opcode(*values)

Opcode values for WebSocket frames.

CONT = 0
TEXT = 1
BINARY = 2
CLOSE = 8
PING = 9
PONG = 10
class websockets.frames.Close(code, reason)

Code and reason for WebSocket close frames.

code

Close code.

Type:

websockets.frames.CloseCode | int

reason

Close reason.

Type:

str

class websockets.frames.CloseCode(*values)

Close code values for WebSocket close frames.

NORMAL_CLOSURE = 1000
GOING_AWAY = 1001
PROTOCOL_ERROR = 1002
UNSUPPORTED_DATA = 1003
NO_STATUS_RCVD = 1005
ABNORMAL_CLOSURE = 1006
INVALID_DATA = 1007
POLICY_VIOLATION = 1008
MESSAGE_TOO_BIG = 1009
MANDATORY_EXTENSION = 1010
INTERNAL_ERROR = 1011
SERVICE_RESTART = 1012
TRY_AGAIN_LATER = 1013
BAD_GATEWAY = 1014
TLS_HANDSHAKE = 1015

HTTP events

class websockets.http11.Request(path, headers, method='GET', protocol='HTTP/1.1', _exception=None)

WebSocket handshake request.

method and path must contain only ASCII characters. headers should contain only ASCII characters; however, non-ASCII header values are tolerated and encoded as ISO-8859-1.

path

Request path, including optional query.

Type:

str

headers

Request headers.

Type:

websockets.datastructures.Headers

method

Request method; WebSocket handshake requests use GET.

Type:

str

protocol

Request protocol; WebSocket handshake requests use HTTP/1.1.

Type:

str

class websockets.http11.Response(status_code, reason_phrase, headers, body=b'', _exception=None)

WebSocket handshake response.

reason_phrase and headers should contain only ASCII characters; however, non-ASCII reason phrases and header values are tolerated and encoded as ISO-8859-1.

status_code

Response code.

Type:

int

reason_phrase

Response reason.

Type:

str

headers

Response headers.

Type:

websockets.datastructures.Headers

body

Response body.

Type:

bytes | bytearray

class websockets.datastructures.Headers(*args, **kwargs)

Efficient data structure for manipulating HTTP headers.

A list of (name, values) is inefficient for lookups.

A dict doesn’t suffice because header names are case-insensitive and multiple occurrences of headers with the same name are possible.

Headers stores HTTP headers in a hybrid data structure to provide efficient insertions and lookups while preserving the original data.

In order to account for multiple values with minimal hassle, Headers follows this logic:

  • When getting a header with headers[name]:
    • if there’s no value, KeyError is raised;

    • if there’s exactly one value, it’s returned;

    • if there’s more than one value, MultipleValuesError is raised.

  • When setting a header with headers[name] = value, the value is appended to the list of values for that header.

  • When deleting a header with del headers[name], all values for that header are removed (this is slow).

Other methods for manipulating headers are consistent with this logic.

As long as no header occurs multiple times, Headers behaves like dict, except keys are lower-cased to provide case-insensitivity.

Two methods support manipulating multiple values explicitly:

  • get_all() returns a list of all values for a header;

  • raw_items() returns an iterator of (name, values) pairs.

Header names and values are expected to contain only ASCII text. However, non-ASCII values happen in practice, even though there is no standard for transmitting non-ASCII data in HTTP headers. Headers supports it by treating it as ISO-8859-1 data. This is a safe and reversible encoding to represent arbitrary data in a str.

When reading headers from the network, if the actual encoding isn’t ISO-8859-1, you must re-encode and decode, e.g.:

value = headers[key].encode("iso-8859-1").decode("utf-8")

Conversely, when sending headers to the network, if you need to use a different encoding, you can encode and decode, e.g.:

headers[key] = value.encode("utf-8").decode("iso-8859-1")

When assigning a value to a header, as a security hardening measure, the value is checked for unsafe characters. The name isn’t checked because it’s usually a constant in code, unlikely to be tainted by user input.

get_all(key)

Return the (possibly empty) list of all values for a header.

Parameters:

key – Header name.

raw_items()

Return an iterator of all values as (name, value) pairs.

exception websockets.datastructures.MultipleValuesError

Exception raised when Headers has multiple values for a key.

URIs

websockets.uri.parse_uri(uri)

Parse and validate a WebSocket URI.

Parameters:

uri – WebSocket URI.

Returns:

Parsed WebSocket URI.

Raises:

InvalidURI – If uri isn’t a valid WebSocket URI.

class websockets.uri.WebSocketURI(secure, host, port, path, query, username=None, password=None)

WebSocket URI.

secure

True for a wss URI, False for a ws URI.

Type:

bool

host

Normalized to lower case.

Type:

str

port

Always set even if it’s the default.

Type:

int

path

May be empty.

Type:

str

query

May be empty if the URI doesn’t include a query component.

Type:

str

username

Available when the URI contains User Information.

Type:

str | None

password

Available when the URI contains User Information.

Type:

str | None