API

Design

websockets provides complete client and server implementations, as shown in the getting started guide. These functions are built on top of low-level APIs reflecting the two phases of the WebSocket protocol:

  1. An opening handshake, in the form of an HTTP Upgrade request;
  2. Data transfer, as framed messages, ending with a closing handshake.

The first phase is designed to integrate with existing HTTP software. websockets provides a minimal implementation to build, parse and validate HTTP requests and responses.

The second phase is the core of the WebSocket protocol. websockets provides a complete implementation on top of asyncio with a simple API.

For convenience, public APIs can be imported directly from the websockets package, unless noted otherwise. Anything that isn’t listed in this document is a private API.

High-level

Server

websockets.server defines the WebSocket server APIs.

await websockets.server.serve(ws_handler, host=None, port=None, *, create_protocol=None, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2 ** 20, max_queue=2 ** 5, read_limit=2 ** 16, write_limit=2 ** 16, loop=None, compression='deflate', origins=None, extensions=None, subprotocols=None, extra_headers=None, process_request=None, select_subprotocol=None, **kwds)

Create, start, and return a WebSocket server on host and port.

Whenever a client connects, the server accepts the connection, creates a WebSocketServerProtocol, performs the opening handshake, and delegates to the connection handler defined by ws_handler. Once the handler completes, either normally or with an exception, the server performs the closing handshake and closes the connection.

Awaiting serve() yields a WebSocketServer. This instance provides close() and wait_closed() methods for terminating the server and cleaning up its resources.

When a server is closed with close(), it closes all connections with close code 1001 (going away). Connections handlers, which are running the ws_handler coroutine, will receive a ConnectionClosedOK exception on their current or next interaction with the WebSocket connection.

serve() can also be used as an asynchronous context manager. In this case, the server is shut down when exiting the context.

serve() is a wrapper around the event loop’s create_server() method. It creates and starts a Server with create_server(). Then it wraps the Server in a WebSocketServer and returns the WebSocketServer.

The ws_handler argument is the WebSocket handler. It must be a coroutine accepting two arguments: a WebSocketServerProtocol and the request URI.

The host and port arguments, as well as unrecognized keyword arguments, are passed along to create_server().

For example, you can set the ssl keyword argument to a SSLContext to enable TLS.

The create_protocol parameter allows customizing the Protocol that manages the connection. It should be a callable or class accepting the same arguments as WebSocketServerProtocol and returning an instance of WebSocketServerProtocol or a subclass. It defaults to WebSocketServerProtocol.

The behavior of ping_interval, ping_timeout, close_timeout, max_size, max_queue, read_limit, and write_limit is described in WebSocketCommonProtocol.

serve() also accepts the following optional arguments:

  • compression is a shortcut to configure compression extensions; by default it enables the “permessage-deflate” extension; set it to None to disable compression
  • origins defines acceptable Origin HTTP headers; include None if the lack of an origin is acceptable
  • extensions is a list of supported extensions in order of decreasing preference
  • subprotocols is a list of supported subprotocols in order of decreasing preference
  • extra_headers sets additional HTTP response headers when the handshake succeeds; it can be a Headers instance, a Mapping, an iterable of (name, value) pairs, or a callable taking the request path and headers in arguments and returning one of the above
  • process_request allows intercepting the HTTP request; it must be a coroutine taking the request path and headers in argument; see process_request() for details
  • select_subprotocol allows customizing the logic for selecting a subprotocol; it must be a callable taking the subprotocols offered by the client and available on the server in argument; see select_subprotocol() for details

Since there’s no useful way to propagate exceptions triggered in handlers, they’re sent to the 'websockets.server' logger instead. Debugging is much easier if you configure logging to print them:

import logging
logger = logging.getLogger('websockets.server')
logger.setLevel(logging.ERROR)
logger.addHandler(logging.StreamHandler())
await websockets.server.unix_serve(ws_handler, path, **kwargs)[source]

Similar to serve(), but for listening on Unix sockets.

This function calls the event loop’s create_unix_server() method.

It is only available on Unix.

It’s useful for deploying a server behind a reverse proxy such as nginx.

Parameters:path (str) – file system path to the Unix socket
Return type:Serve
class websockets.server.WebSocketServer(loop)[source]

WebSocket server returned by serve().

This class provides the same interface as AbstractServer, namely the close() and wait_closed() methods.

It keeps track of WebSocket connections in order to close them properly when shutting down.

Instances of this class store a reference to the Server object returned by create_server() rather than inherit from Server in part because create_server() doesn’t support passing a custom Server class.

close()[source]

Close the server.

This method:

  • closes the underlying Server;
  • rejects new WebSocket connections with an HTTP 503 (service unavailable) error; this happens when the server accepted the TCP connection but didn’t complete the WebSocket opening handshake prior to closing;
  • closes open WebSocket connections with close code 1001 (going away).

close() is idempotent.

Return type:None
await wait_closed()[source]

Wait until the server is closed.

When wait_closed() returns, all TCP connections are closed and all connection handlers have returned.

Return type:None
sockets

List of socket objects the server is listening to.

None if the server is closed.

Return type:Optional[List[socket]]
class websockets.server.WebSocketServerProtocol(ws_handler, ws_server, *, origins=None, extensions=None, subprotocols=None, extra_headers=None, process_request=None, select_subprotocol=None, **kwargs)[source]

Protocol subclass implementing a WebSocket server.

This class inherits most of its methods from WebSocketCommonProtocol.

For the sake of simplicity, it doesn’t rely on a full HTTP implementation. Its support for HTTP responses is very limited.

await handshake(origins=None, available_extensions=None, available_subprotocols=None, extra_headers=None)[source]

Perform the server side of the opening handshake.

Return the path of the URI of the request.

Parameters:
Raises:

InvalidHandshake – if the handshake fails

Return type:

str

await process_request(path, request_headers)[source]

Intercept the HTTP request and return an HTTP response if appropriate.

If process_request returns None, the WebSocket handshake continues. If it returns 3-uple containing a status code, response headers and a response body, that HTTP response is sent and the connection is closed. In that case:

  • The HTTP status must be a HTTPStatus.
  • HTTP headers must be a Headers instance, a Mapping, or an iterable of (name, value) pairs.
  • The HTTP response body must be bytes. It may be empty.

This coroutine may be overridden in a WebSocketServerProtocol subclass, for example:

  • to return a HTTP 200 OK response on a given path; then a load balancer can use this path for a health check;
  • to authenticate the request and return a HTTP 401 Unauthorized or a HTTP 403 Forbidden when authentication fails.

Instead of subclassing, it is possible to override this method by passing a process_request argument to the serve() function or the WebSocketServerProtocol constructor. This is equivalent, except process_request won’t have access to the protocol instance, so it can’t store information for later use.

process_request is expected to complete quickly. If it may run for a long time, then it should await wait_closed() and exit if wait_closed() completes, or else it could prevent the server from shutting down.

Parameters:
  • path (str) – request path, including optional query string
  • request_headers (Headers) – request headers
Return type:

Optional[Tuple[HTTPStatus, Union[Headers, Mapping[str, str], Iterable[Tuple[str, str]]], bytes]]

select_subprotocol(client_subprotocols, server_subprotocols)[source]

Pick a subprotocol among those offered by the client.

If several subprotocols are supported by the client and the server, the default implementation selects the preferred subprotocols by giving equal value to the priorities of the client and the server.

If no subprotocol is supported by the client and the server, it proceeds without a subprotocol.

This is unlikely to be the most useful implementation in practice, as many servers providing a subprotocol will require that the client uses that subprotocol. Such rules can be implemented in a subclass.

Instead of subclassing, it is possible to override this method by passing a select_subprotocol argument to the serve() function or the WebSocketServerProtocol constructor

Parameters:
  • client_subprotocols (Sequence[NewType()(Subprotocol, str)]) – list of subprotocols offered by the client
  • server_subprotocols (Sequence[NewType()(Subprotocol, str)]) – list of subprotocols available on the server
Return type:

Optional[NewType()(Subprotocol, str)]

Client

websockets.client defines the WebSocket client APIs.

await websockets.client.connect(uri, *, create_protocol=None, ping_interval=20, ping_timeout=20, close_timeout=10, max_size=2 ** 20, max_queue=2 ** 5, read_limit=2 ** 16, write_limit=2 ** 16, loop=None, compression='deflate', origin=None, extensions=None, subprotocols=None, extra_headers=None, **kwds)

Connect to the WebSocket server at the given uri.

Awaiting connect() yields a WebSocketClientProtocol which can then be used to send and receive messages.

connect() can also be used as a asynchronous context manager. In that case, the connection is closed when exiting the context.

connect() is a wrapper around the event loop’s create_connection() method. Unknown keyword arguments are passed to create_connection().

For example, you can set the ssl keyword argument to a SSLContext to enforce some TLS settings. When connecting to a wss:// URI, if this argument isn’t provided explicitly, it’s set to True, which means Python’s default SSLContext is used.

You can connect to a different host and port from those found in uri by setting host and port keyword arguments. This only changes the destination of the TCP connection. The host name from uri is still used in the TLS handshake for secure connections and in the Host HTTP header.

The create_protocol parameter allows customizing the Protocol that manages the connection. It should be a callable or class accepting the same arguments as WebSocketClientProtocol and returning an instance of WebSocketClientProtocol or a subclass. It defaults to WebSocketClientProtocol.

The behavior of ping_interval, ping_timeout, close_timeout, max_size, max_queue, read_limit, and write_limit is described in WebSocketCommonProtocol.

connect() also accepts the following optional arguments:

  • compression is a shortcut to configure compression extensions; by default it enables the “permessage-deflate” extension; set it to None to disable compression
  • origin sets the Origin HTTP header
  • extensions is a list of supported extensions in order of decreasing preference
  • subprotocols is a list of supported subprotocols in order of decreasing preference
  • extra_headers sets additional HTTP request headers; it can be a Headers instance, a Mapping, or an iterable of (name, value) pairs
Raises:
  • InvalidURI – if uri is invalid
  • InvalidHandshake – if the opening handshake fails
await websockets.client.unix_connect(path, uri='ws://localhost/', **kwargs)[source]

Similar to connect(), but for connecting to a Unix socket.

This function calls the event loop’s create_unix_connection() method.

It is only available on Unix.

It’s mainly useful for debugging servers listening on Unix sockets.

Parameters:
  • path (str) – file system path to the Unix socket
  • uri (str) – WebSocket URI
Return type:

Connect

class websockets.client.WebSocketClientProtocol(*, origin=None, extensions=None, subprotocols=None, extra_headers=None, **kwargs)[source]

Protocol subclass implementing a WebSocket client.

This class inherits most of its methods from WebSocketCommonProtocol.

await handshake(wsuri, origin=None, available_extensions=None, available_subprotocols=None, extra_headers=None)[source]

Perform the client side of the opening handshake.

Parameters:
Raises:

InvalidHandshake – if the handshake fails

Return type:

None

Shared

websockets.protocol handles WebSocket control and data frames.

See sections 4 to 8 of RFC 6455.

class websockets.protocol.WebSocketCommonProtocol(*, ping_interval=20, ping_timeout=20, close_timeout=None, max_size=1048576, max_queue=32, read_limit=65536, write_limit=65536, loop=None, host=None, port=None, secure=None, legacy_recv=False, timeout=None)[source]

Protocol subclass implementing the data transfer phase.

Once the WebSocket connection is established, during the data transfer phase, the protocol is almost symmetrical between the server side and the client side. WebSocketCommonProtocol implements logic that’s shared between servers and clients..

Subclasses such as WebSocketServerProtocol and WebSocketClientProtocol implement the opening handshake, which is different between servers and clients.

WebSocketCommonProtocol performs four functions:

  • It runs a task that stores incoming data frames in a queue and makes them available with the recv() coroutine.
  • It sends outgoing data frames with the send() coroutine.
  • It deals with control frames automatically.
  • It performs the closing handshake.

WebSocketCommonProtocol supports asynchronous iteration:

async for message in websocket:
    await process(message)

The iterator yields incoming messages. It exits normally when the connection is closed with the close code 1000 (OK) or 1001 (going away). It raises a ConnectionClosedError exception when the connection is closed with any other code.

Once the connection is open, a Ping frame is sent every ping_interval seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ping_interval to None to disable this behavior.

If the corresponding Pong frame isn’t received within ping_timeout seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ping_timeout to None to disable this behavior.

The close_timeout parameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection. close() completes in at most 4 * close_timeout on the server side and 5 * close_timeout on the client side.

close_timeout needs to be a parameter of the protocol because websockets usually calls close() implicitly:

  • on the server side, when the connection handler terminates,
  • on the client side, when exiting the context manager for the connection.

To apply a timeout to any other API, wrap it in wait_for().

The max_size parameter enforces the maximum size for incoming messages in bytes. The default value is 1 MiB. None disables the limit. If a message larger than the maximum size is received, recv() will raise ConnectionClosedError and the connection will be closed with code 1009.

The max_queue parameter sets the maximum length of the queue that holds incoming messages. The default value is 32. None disables the limit. Messages are added to an in-memory queue when they’re received; then recv() pops from that queue. In order to prevent excessive memory consumption when messages are received faster than they can be processed, the queue must be bounded. If the queue fills up, the protocol stops processing incoming data until recv() is called. In this situation, various receive buffers (at least in asyncio and in the OS) will fill up, then the TCP receive window will shrink, slowing down transmission to avoid packet loss.

Since Python can use up to 4 bytes of memory to represent a single character, each connection may use up to 4 * max_size * max_queue bytes of memory to store incoming messages. By default, this is 128 MiB. You may want to lower the limits, depending on your application’s requirements.

The read_limit argument sets the high-water limit of the buffer for incoming bytes. The low-water limit is half the high-water limit. The default value is 64 KiB, half of asyncio’s default (based on the current implementation of StreamReader).

The write_limit argument sets the high-water limit of the buffer for outgoing bytes. The low-water limit is a quarter of the high-water limit. The default value is 64 KiB, equal to asyncio’s default (based on the current implementation of FlowControlMixin).

As soon as the HTTP request and response in the opening handshake are processed:

  • the request path is available in the path attribute;
  • the request and response HTTP headers are available in the request_headers and response_headers attributes, which are Headers instances.

If a subprotocol was negotiated, it’s available in the subprotocol attribute.

Once the connection is closed, the code is available in the close_code attribute and the reason in close_reason.

All these attributes must be treated as read-only.

await close(code=1000, reason='')[source]

Perform the closing handshake.

close() waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there’s no need to await wait_closed(); close() already does it.

close() is idempotent: it doesn’t do anything once the connection is closed.

Wrapping close() in create_task() is safe, given that errors during connection termination aren’t particularly useful.

Canceling close() is discouraged. If it takes too long, you can set a shorter close_timeout. If you don’t want to wait, let the Python process exit, then the OS will close the TCP connection.

Parameters:
  • code (int) – WebSocket close code
  • reason (str) – WebSocket close reason
Return type:

None

await wait_closed()[source]

Wait until the connection is closed.

This is identical to closed, except it can be awaited.

This can make it easier to handle connection termination, regardless of its cause, in tasks that interact with the WebSocket connection.

Return type:None
await recv()[source]

Receive the next message.

Return a str for a text frame and bytes for a binary frame.

When the end of the message stream is reached, recv() raises ConnectionClosed. Specifically, it raises ConnectionClosedOK after a normal connection closure and ConnectionClosedError after a protocol error or a network failure.

Changed in version 3.0: recv() used to return None instead. Refer to the changelog for details.

Canceling recv() is safe. There’s no risk of losing the next message. The next invocation of recv() will return it. This makes it possible to enforce a timeout by wrapping recv() in wait_for().

Raises:
Return type:

Union[str, bytes]

await send(message)[source]

Send a message.

A string (str) is sent as a Text frame. A bytestring or bytes-like object (bytes, bytearray, or memoryview) is sent as a Binary frame.

send() also accepts an iterable or an asynchronous iterable of strings, bytestrings, or bytes-like objects. In that case the message is fragmented. Each item is treated as a message fragment and sent in its own frame. All items must be of the same type, or else send() will raise a TypeError and the connection will be closed.

Canceling send() is discouraged. Instead, you should close the connection with close(). Indeed, there only two situations where send() yields control to the event loop:

  1. The write buffer is full. If you don’t want to wait until enough data is sent, your only alternative is to close the connection. close() will likely time out then abort the TCP connection.
  2. message is an asynchronous iterator. Stopping in the middle of a fragmented message will cause a protocol error. Closing the connection has the same effect.
Raises:TypeError – for unsupported inputs
Return type:None
await ping(data=None)[source]

Send a ping.

Return a Future which will be completed when the corresponding pong is received and which you may ignore if you don’t want to wait.

A ping may serve as a keepalive or as a check that the remote endpoint received all messages up to this point:

pong_waiter = await ws.ping()
await pong_waiter   # only if you want to wait for the pong

By default, the ping contains four random bytes. This payload may be overridden with the optional data argument which must be a string (which will be encoded to UTF-8) or a bytes-like object.

Canceling ping() is discouraged. If ping() doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.

Canceling the Future returned by ping() has no effect.

Return type:Awaitable[None]
await pong(data=b'')[source]

Send a pong.

An unsolicited pong may serve as a unidirectional heartbeat.

The payload may be set with the optional data argument which must be a string (which will be encoded to UTF-8) or a bytes-like object.

Canceling pong() is discouraged for the same reason as ping().

Return type:None
local_address

Local address of the connection.

This is a (host, port) tuple or None if the connection hasn’t been established yet.

Return type:Any
remote_address

Remote address of the connection.

This is a (host, port) tuple or None if the connection hasn’t been established yet.

Return type:Any
open

True when the connection is usable.

It may be used to detect disconnections. However, this approach is discouraged per the EAFP principle.

When open is False, using the connection raises a ConnectionClosed exception.

Return type:bool
closed

True once the connection is closed.

Be aware that both open and closed are False during the opening and closing sequences.

Return type:bool

Types

websockets.typing.Data = typing.Union[str, bytes]

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

  • The arguments must be types and there must be at least one.

  • None as an argument is a special case and is replaced by type(None).

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str]
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • When two arguments have a subclass relationship, the least derived argument is kept, e.g.:

    class Employee: pass
    class Manager(Employee): pass
    Union[int, Employee, Manager] == Union[int, Employee]
    Union[Manager, int, Employee] == Union[int, Employee]
    Union[Employee, Manager] == Employee
    
  • Similar for object:

    Union[int, object] == object
    
  • You cannot subclass or instantiate a union.

  • You can use Optional[X] as a shorthand for Union[X, None].

Per-Message Deflate Extension

websockets.extensions.permessage_deflate implements the Compression Extensions for WebSocket as specified in RFC 7692.

class websockets.extensions.permessage_deflate.ServerPerMessageDeflateFactory(server_no_context_takeover=False, client_no_context_takeover=False, server_max_window_bits=None, client_max_window_bits=None, compress_settings=None)[source]

Server-side extension factory for the Per-Message Deflate extension.

Parameters behave as described in section 7.1 of RFC 7692. Set them to True to include them in the negotiation offer without a value or to an integer value to include them with this value.

Parameters:
  • server_no_context_takeover (bool) – defaults to False
  • client_no_context_takeover (bool) – defaults to False
  • server_max_window_bits (Optional[int]) – optional, defaults to None
  • client_max_window_bits (Optional[int]) – optional, defaults to None
  • compress_settings (Optional[Dict[str, Any]]) – optional, keyword arguments for zlib.compressobj(), excluding wbits
class websockets.extensions.permessage_deflate.ClientPerMessageDeflateFactory(server_no_context_takeover=False, client_no_context_takeover=False, server_max_window_bits=None, client_max_window_bits=None, compress_settings=None)[source]

Client-side extension factory for the Per-Message Deflate extension.

Parameters behave as described in section 7.1 of RFC 7692. Set them to True to include them in the negotiation offer without a value or to an integer value to include them with this value.

Parameters:
  • server_no_context_takeover (bool) – defaults to False
  • client_no_context_takeover (bool) – defaults to False
  • server_max_window_bits (Optional[int]) – optional, defaults to None
  • client_max_window_bits (Optional[int]) – optional, defaults to None
  • compress_settings (Optional[Dict[str, Any]]) – optional, keyword arguments for zlib.compressobj(), excluding wbits

HTTP Basic Auth

websockets.auth provides HTTP Basic Authentication according to RFC 7235 and RFC 7617.

websockets.auth.basic_auth_protocol_factory(realm, credentials=None, check_credentials=None, create_protocol=<class 'websockets.auth.BasicAuthWebSocketServerProtocol'>)[source]

Protocol factory that enforces HTTP Basic Auth.

basic_auth_protocol_factory is designed to integrate with serve() like this:

websockets.serve(
    ...,
    create_protocol=websockets.basic_auth_protocol_factory(
        realm="my dev server",
        credentials=("hello", "iloveyou"),
    )
)

realm indicates the scope of protection. It should contain only ASCII characters because the encoding of non-ASCII characters is undefined. Refer to section 2.2 of RFC 7235 for details.

credentials defines hard coded authorized credentials. It can be a (username, password) pair or a list of such pairs.

check_credentials defines a coroutine that checks whether credentials are authorized. This coroutine receives username and password arguments and returns a bool.

One of credentials or check_credentials must be provided but not both.

By default, basic_auth_protocol_factory creates a factory for building BasicAuthWebSocketServerProtocol instances. You can override this with the create_protocol parameter.

Parameters:
Raises:

TypeError – if the credentials argument has the wrong type

Return type:

Callable[[Any], BasicAuthWebSocketServerProtocol]

class websockets.auth.BasicAuthWebSocketServerProtocol(*args, realm, check_credentials, **kwargs)[source]

WebSocket server protocol that enforces HTTP Basic Auth.

await process_request(path, request_headers)[source]

Check HTTP Basic Auth and return a HTTP 401 or 403 response if needed.

If authentication succeeds, the username of the authenticated user is stored in the username attribute.

Return type:Optional[Tuple[HTTPStatus, Union[Headers, Mapping[str, str], Iterable[Tuple[str, str]]], bytes]]

Exceptions

websockets.exceptions defines the following exception hierarchy:

exception websockets.exceptions.WebSocketException[source]

Base class for all exceptions defined by websockets.

exception websockets.exceptions.ConnectionClosed(code, reason)[source]

Raised when trying to interact with a closed connection.

Provides the connection close code and reason in its code and reason attributes respectively.

exception websockets.exceptions.ConnectionClosedError(code, reason)[source]

Like ConnectionClosed, when the connection terminated with an error.

This means the close code is different from 1000 (OK) and 1001 (going away).

exception websockets.exceptions.ConnectionClosedOK(code, reason)[source]

Like ConnectionClosed, when the connection terminated properly.

This means the close code is 1000 (OK) or 1001 (going away).

exception websockets.exceptions.InvalidHandshake[source]

Raised during the handshake when the WebSocket connection fails.

exception websockets.exceptions.SecurityError[source]

Raised when a handshake request or response breaks a security rule.

Security limits are hard coded.

exception websockets.exceptions.InvalidMessage[source]

Raised when a handshake request or response is malformed.

exception websockets.exceptions.InvalidHeader(name, value=None)[source]

Raised when a HTTP header doesn’t have a valid format or value.

exception websockets.exceptions.InvalidHeaderFormat(name, error, header, pos)[source]

Raised when a HTTP header cannot be parsed.

The format of the header doesn’t match the grammar for that header.

exception websockets.exceptions.InvalidHeaderValue(name, value=None)[source]

Raised when a HTTP header has a wrong value.

The format of the header is correct but a value isn’t acceptable.

exception websockets.exceptions.InvalidOrigin(origin)[source]

Raised when the Origin header in a request isn’t allowed.

exception websockets.exceptions.InvalidUpgrade(name, value=None)[source]

Raised when the Upgrade or Connection header isn’t correct.

exception websockets.exceptions.InvalidStatusCode(status_code)[source]

Raised when a handshake response status code is invalid.

The integer status code is available in the status_code attribute.

exception websockets.exceptions.NegotiationError[source]

Raised when negotiating an extension fails.

exception websockets.exceptions.DuplicateParameter(name)[source]

Raised when a parameter name is repeated in an extension header.

exception websockets.exceptions.InvalidParameterName(name)[source]

Raised when a parameter name in an extension header is invalid.

exception websockets.exceptions.InvalidParameterValue(name, value)[source]

Raised when a parameter value in an extension header is invalid.

exception websockets.exceptions.AbortHandshake(status, headers, body=b'')[source]

Raised to abort the handshake on purpose and return a HTTP response.

This exception is an implementation detail.

The public API is process_request().

exception websockets.exceptions.RedirectHandshake(uri)[source]

Raised when a handshake gets redirected.

This exception is an implementation detail.

exception websockets.exceptions.InvalidState[source]

Raised when an operation is forbidden in the current state.

This exception is an implementation detail.

It should never be raised in normal circumstances.

exception websockets.exceptions.InvalidURI(uri)[source]

Raised when connecting to an URI that isn’t a valid WebSocket URI.

exception websockets.exceptions.PayloadTooBig[source]

Raised when receiving a frame with a payload exceeding the maximum size.

exception websockets.exceptions.ProtocolError[source]

Raised when the other side breaks the protocol.

websockets.exceptions.WebSocketProtocolError

alias of websockets.exceptions.ProtocolError

Low-level

Opening handshake

websockets.handshake provides helpers for the WebSocket handshake.

See section 4 of RFC 6455.

Some checks cannot be performed because they depend too much on the context; instead, they’re documented below.

To accept a connection, a server must:

  • Read the request, check that the method is GET, and check the headers with check_request(),
  • Send a 101 response to the client with the headers created by build_response() if the request is valid; otherwise, send an appropriate HTTP error code.

To open a connection, a client must:

  • Send a GET request to the server with the headers created by build_request(),
  • Read the response, check that the status code is 101, and check the headers with check_response().
websockets.handshake.build_request(headers)[source]

Build a handshake request to send to the server.

Update request headers passed in argument.

Parameters:headers (Headers) – request headers
Return type:str
Returns:key which must be passed to check_response()
websockets.handshake.check_request(headers)[source]

Check a handshake request received from the client.

This function doesn’t verify that the request is an HTTP/1.1 or higher GET request and doesn’t perform Host and Origin checks. These controls are usually performed earlier in the HTTP request handling code. They’re the responsibility of the caller.

Parameters:headers (Headers) – request headers
Return type:str
Returns:key which must be passed to build_response()
Raises:InvalidHandshake – if the handshake request is invalid; then the server must return 400 Bad Request error
websockets.handshake.build_response(headers, key)[source]

Build a handshake response to send to the client.

Update response headers passed in argument.

Parameters:
Return type:

None

websockets.handshake.check_response(headers, key)[source]

Check a handshake response received from the server.

This function doesn’t verify that the response is an HTTP/1.1 or higher response with a 101 status code. These controls are the responsibility of the caller.

Parameters:
Raises:

InvalidHandshake – if the handshake response is invalid

Return type:

None

Data transfer

websockets.framing reads and writes WebSocket frames.

It deals with a single frame at a time. Anything that depends on the sequence of frames is implemented in websockets.protocol.

See section 5 of RFC 6455.

class websockets.framing.Frame[source]

WebSocket frame.

Parameters:
  • fin (bool) – FIN bit
  • rsv1 (bool) – RSV1 bit
  • rsv2 (bool) – RSV2 bit
  • rsv3 (bool) – RSV3 bit
  • opcode (int) – opcode
  • data (bytes) – payload data

Only these fields are needed. The MASK bit, payload length and masking-key are handled on the fly by read() and write().

check()[source]

Check that reserved bits and opcode have acceptable values.

Raises:ProtocolError – if a reserved bit or the opcode is invalid
Return type:None
classmethod await read(reader, *, mask, max_size=None, extensions=None)[source]

Read a WebSocket frame.

Parameters:
  • reader (Callable[[int], Awaitable[bytes]]) – coroutine that reads exactly the requested number of bytes, unless the end of file is reached
  • mask (bool) – whether the frame should be masked i.e. whether the read happens on the server side
  • max_size (Optional[int]) – maximum payload size in bytes
  • extensions (Optional[Sequence[Extension]]) – list of classes with a decode() method that transforms the frame and return a new frame; extensions are applied in reverse order
Raises:
Return type:

Frame

write(writer, *, mask, extensions=None)[source]

Write a WebSocket frame.

Parameters:
  • frame – frame to write
  • writer (Callable[[bytes], Any]) – function that writes bytes
  • mask (bool) – whether the frame should be masked i.e. whether the write happens on the client side
  • extensions (Optional[Sequence[Extension]]) – list of classes with an encode() method that transform the frame and return a new frame; extensions are applied in order
Raises:

ProtocolError – if the frame contains incorrect values

Return type:

None

websockets.framing.prepare_data(data)[source]

Convert a string or byte-like object to an opcode and a bytes-like object.

This function is designed for data frames.

If data is a str, return OP_TEXT and a bytes object encoding data in UTF-8.

If data is a bytes-like object, return OP_BINARY and a bytes-like object.

Raises:TypeError – if data doesn’t have a supported type
Return type:Tuple[int, bytes]
websockets.framing.encode_data(data)[source]

Convert a string or byte-like object to bytes.

This function is designed for ping and pong frames.

If data is a str, return a bytes object encoding data in UTF-8.

If data is a bytes-like object, return a bytes object.

Raises:TypeError – if data doesn’t have a supported type
Return type:bytes
websockets.framing.parse_close(data)[source]

Parse the payload from a close frame.

Return (code, reason).

Raises:
Return type:

Tuple[int, str]

websockets.framing.serialize_close(code, reason)[source]

Serialize the payload for a close frame.

This is the reverse of parse_close().

Return type:bytes

URI parser

websockets.uri parses WebSocket URIs.

See section 3 of RFC 6455.

websockets.uri.parse_uri(uri)[source]

Parse and validate a WebSocket URI.

Raises:ValueError – if uri isn’t a valid WebSocket URI.
Return type:WebSocketURI
class websockets.uri.WebSocketURI[source]

WebSocket URI.

Parameters:
  • secure (bool) – secure flag
  • host (str) – lower-case host
  • port (int) – port, always set even if it’s the default
  • resource_name (str) – path and optional query
  • user_info (str) – (username, password) tuple when the URI contains User Information, else None.

Utilities

websockets.headers provides parsers and serializers for HTTP headers used in WebSocket handshake messages.

These APIs cannot be imported from websockets. They must be imported from websockets.headers.

websockets.headers.parse_connection(header)[source]

Parse a Connection header.

Return a list of HTTP connection options.

Parameters:header (str) – value of the Connection header
Raises:InvalidHeaderFormat – on invalid inputs.
Return type:List[NewType()(ConnectionOption, str)]
websockets.headers.parse_upgrade(header)[source]

Parse an Upgrade header.

Return a list of HTTP protocols.

Parameters:header (str) – value of the Upgrade header
Raises:InvalidHeaderFormat – on invalid inputs.
Return type:List[NewType()(UpgradeProtocol, str)]
websockets.headers.parse_extension(header)[source]

Parse a Sec-WebSocket-Extensions header.

Return a list of WebSocket extensions and their parameters in this format:

[
    (
        'extension name',
        [
            ('parameter name', 'parameter value'),
            ....
        ]
    ),
    ...
]

Parameter values are None when no value is provided.

Raises:InvalidHeaderFormat – on invalid inputs.
Return type:List[Tuple[str, List[Tuple[str, Optional[str]]]]]
websockets.headers.build_extension(extensions)[source]

Build a Sec-WebSocket-Extensions header.

This is the reverse of parse_extension().

Return type:str
websockets.headers.parse_subprotocol(header)[source]

Parse a Sec-WebSocket-Protocol header.

Return a list of WebSocket subprotocols.

Raises:InvalidHeaderFormat – on invalid inputs.
Return type:List[NewType()(Subprotocol, str)]
websockets.headers.build_subprotocol(protocols)[source]

Build a Sec-WebSocket-Protocol header.

This is the reverse of parse_subprotocol().

Return type:str
websockets.headers.build_www_authenticate_basic(realm)[source]

Build a WWW-Authenticate header for HTTP Basic Auth.

Parameters:realm (str) – authentication realm
Return type:str
websockets.headers.parse_authorization_basic(header)[source]

Parse an Authorization header for HTTP Basic Auth.

Return a (username, password) tuple.

Parameters:

header (str) – value of the Authorization header

Raises:
Return type:

Tuple[str, str]

websockets.headers.build_authorization_basic(username, password)[source]

Build an Authorization header for HTTP Basic Auth.

This is the reverse of parse_authorization_basic().

Return type:str

websockets.http module provides basic HTTP/1.1 support. It is merely :adequate for WebSocket handshake messages.

These APIs cannot be imported from websockets. They must be imported from websockets.http.

await websockets.http.read_request(stream)[source]

Read an HTTP/1.1 GET request and returns (path, headers).

path isn’t URL-decoded or validated in any way.

path and headers are expected to contain only ASCII characters. Other characters are represented with surrogate escapes.

read_request() doesn’t attempt to read the request body because WebSocket handshake requests don’t have one. If the request contains a body, it may be read from stream after this coroutine returns.

Parameters:

stream (StreamReader) – input to read the request from

Raises:
  • EOFError – if the connection is closed without a full HTTP request
  • SecurityError – if the request exceeds a security limit
  • ValueError – if the request isn’t well formatted
Return type:

Tuple[str, Headers]

await websockets.http.read_response(stream)[source]

Read an HTTP/1.1 response and returns (status_code, reason, headers).

reason and headers are expected to contain only ASCII characters. Other characters are represented with surrogate escapes.

read_request() doesn’t attempt to read the response body because WebSocket handshake responses don’t have one. If the response contains a body, it may be read from stream after this coroutine returns.

Parameters:

stream (StreamReader) – input to read the response from

Raises:
  • EOFError – if the connection is closed without a full HTTP response
  • SecurityError – if the response exceeds a security limit
  • ValueError – if the response isn’t well formatted
Return type:

Tuple[int, str, Headers]

class websockets.http.Headers(*args, **kwargs)[source]

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 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.
clear()[source]

Remove all headers.

Return type:None
get_all(key)[source]

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

Parameters:key (str) – header name
Return type:List[str]
raw_items()[source]

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

Return type:Iterator[Tuple[str, str]]
exception websockets.http.MultipleValuesError[source]

Exception raised when Headers has more than one value for a key.