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:
An opening handshake, in the form of an HTTP Upgrade request;
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, *, path=None, create_protocol=None, ping_interval=20, ping_timeout=20, close_timeout=None, max_size=1048576, max_queue=32, read_limit=65536, write_limit=65536, loop=None, legacy_recv=False, klass=None, timeout=None, compression='deflate', origins=None, extensions=None, subprotocols=None, extra_headers=None, process_request=None, select_subprotocol=None, **kwargs)¶
Create, start, and return a WebSocket server on
hostandport.Whenever a client connects, the server accepts the connection, creates a
WebSocketServerProtocol, performs the opening handshake, and delegates to the connection handler defined byws_handler. Once the handler completes, either normally or with an exception, the server performs the closing handshake and closes the connection.Awaiting
serve()yields aWebSocketServer. This instance providesclose()andwait_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 thews_handlercoroutine, will receive aConnectionClosedOKexception 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’screate_server()method. It creates and starts aServerwithcreate_server(). Then it wraps theServerin aWebSocketServerand returns theWebSocketServer.The
ws_handlerargument is the WebSocket handler. It must be a coroutine accepting two arguments: aWebSocketServerProtocoland the request URI.The
hostandportarguments, as well as unrecognized keyword arguments, are passed along tocreate_server().For example, you can set the
sslkeyword argument to aSSLContextto enable TLS.The
create_protocolparameter allows customizing theProtocolthat manages the connection. It should be a callable or class accepting the same arguments asWebSocketServerProtocoland returning an instance ofWebSocketServerProtocolor a subclass. It defaults toWebSocketServerProtocol.The behavior of
ping_interval,ping_timeout,close_timeout,max_size,max_queue,read_limit, andwrite_limitis described inWebSocketCommonProtocol.serve()also accepts the following optional arguments:compressionis a shortcut to configure compression extensions; by default it enables the “permessage-deflate” extension; set it toNoneto disable compressionoriginsdefines acceptable Origin HTTP headers; includeNoneif the lack of an origin is acceptableextensionsis a list of supported extensions in order of decreasing preferencesubprotocolsis a list of supported subprotocols in order of decreasing preferenceextra_headerssets additional HTTP response headers when the handshake succeeds; it can be aHeadersinstance, aMapping, an iterable of(name, value)pairs, or a callable taking the request path and headers in arguments and returning one of the aboveprocess_requestallows intercepting the HTTP request; it must be a coroutine taking the request path and headers in argument; seeprocess_request()for detailsselect_subprotocolallows 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; seeselect_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 theclose()andwait_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
Serverobject returned bycreate_server()rather than inherit fromServerin part becausecreate_server()doesn’t support passing a customServerclass.- close()[source]¶
Close the server.
This method: :rtype:
Nonecloses 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.
- 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:
- 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]¶
Protocolsubclass 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:
origins (
Optional[Sequence[Optional[NewType()(Origin,str)]]]) – list of acceptable values of the Origin HTTP header; includeNoneif the lack of an origin is acceptableavailable_extensions (
Optional[Sequence[ServerExtensionFactory]]) – list of supported extensions in the order in which they should be usedavailable_subprotocols (
Optional[Sequence[NewType()(Subprotocol,str)]]) – list of supported subprotocols in order of decreasing preferenceextra_headers (
Union[Headers,Mapping[str,str],Iterable[Tuple[str,str]],Callable[[str,Headers],Union[Headers,Mapping[str,str],Iterable[Tuple[str,str]]]],None]) – sets additional HTTP response headers when the handshake succeeds; it can be aHeadersinstance, aMapping, an iterable of(name, value)pairs, or a callable taking the request path and headers in arguments and returning one of the above.
- Raises:
InvalidHandshake – if the handshake fails
- Return type:
- await process_request(path, request_headers)[source]¶
Intercept the HTTP request and return an HTTP response if appropriate.
If
process_requestreturnsNone, 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
Headersinstance, aMapping, 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
WebSocketServerProtocolsubclass, 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_requestargument to theserve()function or theWebSocketServerProtocolconstructor. This is equivalent, exceptprocess_requestwon’t have access to the protocol instance, so it can’t store information for later use.process_requestis expected to complete quickly. If it may run for a long time, then it should awaitwait_closed()and exit ifwait_closed()completes, or else it could prevent the server from shutting down.
- 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_subprotocolargument to theserve()function or theWebSocketServerProtocolconstructor
Client¶
websockets.client defines the WebSocket client APIs.
- await websockets.client.connect(uri, *, path=None, create_protocol=None, ping_interval=20, ping_timeout=20, close_timeout=None, max_size=1048576, max_queue=32, read_limit=65536, write_limit=65536, loop=None, legacy_recv=False, klass=None, timeout=None, compression='deflate', origin=None, extensions=None, subprotocols=None, extra_headers=None, **kwargs)¶
Connect to the WebSocket server at the given
uri.Awaiting
connect()yields aWebSocketClientProtocolwhich 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’screate_connection()method. Unknown keyword arguments are passed tocreate_connection().For example, you can set the
sslkeyword argument to aSSLContextto enforce some TLS settings. When connecting to awss://URI, if this argument isn’t provided explicitly,ssl.create_default_context()is called to create a context.You can connect to a different host and port from those found in
uriby settinghostandportkeyword arguments. This only changes the destination of the TCP connection. The host name fromuriis still used in the TLS handshake for secure connections and in theHostHTTP header.The
create_protocolparameter allows customizing theProtocolthat manages the connection. It should be a callable or class accepting the same arguments asWebSocketClientProtocoland returning an instance ofWebSocketClientProtocolor a subclass. It defaults toWebSocketClientProtocol.The behavior of
ping_interval,ping_timeout,close_timeout,max_size,max_queue,read_limit, andwrite_limitis described inWebSocketCommonProtocol.connect()also accepts the following optional arguments:compressionis a shortcut to configure compression extensions; by default it enables the “permessage-deflate” extension; set it toNoneto disable compressionoriginsets the Origin HTTP headerextensionsis a list of supported extensions in order of decreasing preferencesubprotocolsis a list of supported subprotocols in order of decreasing preferenceextra_headerssets additional HTTP request headers; it can be aHeadersinstance, aMapping, or an iterable of(name, value)pairs
- Raises:
InvalidURI – if
uriis invalidInvalidHandshake – 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.
- class websockets.client.WebSocketClientProtocol(*, origin=None, extensions=None, subprotocols=None, extra_headers=None, **kwargs)[source]¶
Protocolsubclass 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:
origin (
Optional[NewType()(Origin,str)]) – sets the Origin HTTP headeravailable_extensions (
Optional[Sequence[ClientExtensionFactory]]) – list of supported extensions in the order in which they should be usedavailable_subprotocols (
Optional[Sequence[NewType()(Subprotocol,str)]]) – list of supported subprotocols in order of decreasing preferenceextra_headers (
Union[Headers,Mapping[str,str],Iterable[Tuple[str,str]],None]) – sets additional HTTP request headers; it must be aHeadersinstance, aMapping, or an iterable of(name, value)pairs
- Raises:
InvalidHandshake – if the handshake fails
- Return type:
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]¶
Protocolsubclass 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.
WebSocketCommonProtocolimplements logic that’s shared between servers and clients..Subclasses such as
WebSocketServerProtocolandWebSocketClientProtocolimplement the opening handshake, which is different between servers and clients.WebSocketCommonProtocolperforms 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.
WebSocketCommonProtocolsupports 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
ConnectionClosedErrorexception when the connection is closed with any other code.Once the connection is open, a Ping frame is sent every
ping_intervalseconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Setping_intervaltoNoneto disable this behavior.If the corresponding Pong frame isn’t received within
ping_timeoutseconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Setping_timeouttoNoneto disable this behavior.The
close_timeoutparameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection.close()completes in at most4 * close_timeouton the server side and5 * close_timeouton the client side.close_timeoutneeds to be a parameter of the protocol becausewebsocketsusually callsclose()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_sizeparameter enforces the maximum size for incoming messages in bytes. The default value is 1 MiB.Nonedisables the limit. If a message larger than the maximum size is received,recv()will raiseConnectionClosedErrorand the connection will be closed with code 1009.The
max_queueparameter sets the maximum length of the queue that holds incoming messages. The default value is32.Nonedisables the limit. Messages are added to an in-memory queue when they’re received; thenrecv()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 untilrecv()is called. In this situation, various receive buffers (at least inasyncioand 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_queuebytes 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_limitargument 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 ofStreamReader).The
write_limitargument 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 ofFlowControlMixin).As soon as the HTTP request and response in the opening handshake are processed:
the request path is available in the
pathattribute;the request and response HTTP headers are available in the
request_headersandresponse_headersattributes, which areHeadersinstances.
If a subprotocol was negotiated, it’s available in the
subprotocolattribute.Once the connection is closed, the code is available in the
close_codeattribute and the reason inclose_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 awaitwait_closed();close()already does it.close()is idempotent: it doesn’t do anything once the connection is closed.Wrapping
close()increate_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 shorterclose_timeout. If you don’t want to wait, let the Python process exit, then the OS will close the TCP connection.
- 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:
- await recv()[source]¶
Receive the next message.
Return a
strfor a text frame andbytesfor a binary frame.When the end of the message stream is reached,
recv()raisesConnectionClosed. Specifically, it raisesConnectionClosedOKafter a normal connection closure andConnectionClosedErrorafter a protocol error or a network failure. :rtype:Union[str,bytes]Changed in version 3.0:
recv()used to returnNoneinstead. Refer to the changelog for details.Canceling
recv()is safe. There’s no risk of losing the next message. The next invocation ofrecv()will return it. This makes it possible to enforce a timeout by wrappingrecv()inwait_for().- Raises:
ConnectionClosed – when the connection is closed
RuntimeError – if two coroutines call
recv()concurrently
- await send(message)[source]¶
Send a message.
A string (
str) is sent as a Text frame. A bytestring or bytes-like object (bytes,bytearray, ormemoryview) is sent as a Binary frame. :rtype:Nonesend()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 elsesend()will raise aTypeErrorand the connection will be closed.Canceling
send()is discouraged. Instead, you should close the connection withclose(). Indeed, there only two situations wheresend()yields control to the event loop: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.messageis 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
- await ping(data=None)[source]¶
Send a ping.
Return a
Futurewhich 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
dataargument which must be a string (which will be encoded to UTF-8) or a bytes-like object.Canceling
ping()is discouraged. Ifping()doesn’t return immediately, it means the write buffer is full. If you don’t want to wait, you should close the connection.
- 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
dataargument 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 asping().- Return type:
- local_address¶
Local address of the connection.
This is a
(host, port)tuple orNoneif the connection hasn’t been established yet.
- remote_address¶
Remote address of the connection.
This is a
(host, port)tuple orNoneif the connection hasn’t been established yet.
- open¶
Truewhen the connection is usable.It may be used to detect disconnections. However, this approach is discouraged per the EAFP principle.
When
openisFalse, using the connection raises aConnectionClosedexception.
Types¶
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
Trueto 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 toFalseclient_no_context_takeover (
bool) – defaults toFalseserver_max_window_bits (
Optional[int]) – optional, defaults toNoneclient_max_window_bits (
Optional[int]) – optional, defaults toNonecompress_settings (
Optional[Dict[str,Any]]) – optional, keyword arguments forzlib.compressobj(), excludingwbits
- 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
Trueto 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 toFalseclient_no_context_takeover (
bool) – defaults toFalseserver_max_window_bits (
Optional[int]) – optional, defaults toNoneclient_max_window_bits (
Union[int,bool,None]) – optional, defaults toNonecompress_settings (
Optional[Dict[str,Any]]) – optional, keyword arguments forzlib.compressobj(), excludingwbits
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_factoryis designed to integrate withserve()like this:websockets.serve( ..., create_protocol=websockets.basic_auth_protocol_factory( realm="my dev server", credentials=("hello", "iloveyou"), ) )
realmindicates 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.credentialsdefines hard coded authorized credentials. It can be a(username, password)pair or a list of such pairs.check_credentialsdefines a coroutine that checks whether credentials are authorized. This coroutine receivesusernameandpasswordarguments and returns abool.One of
credentialsorcheck_credentialsmust be provided but not both.By default,
basic_auth_protocol_factorycreates a factory for buildingBasicAuthWebSocketServerProtocolinstances. You can override this with thecreate_protocolparameter.- Parameters:
- Raises:
TypeError – if the credentials argument has the wrong type
- Return type:
- class websockets.auth.BasicAuthWebSocketServerProtocol(*args, realm, check_credentials, **kwargs)[source]¶
WebSocket server protocol that enforces HTTP Basic Auth.
Exceptions¶
websockets.exceptions defines the following exception hierarchy:
- 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.ConnectionClosed(code, reason)[source]¶
Raised when trying to interact with a closed connection.
Provides the connection close code and reason in its
codeandreasonattributes 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.DuplicateParameter(name)[source]¶
Raised when a parameter name is repeated in an extension header.
- exception websockets.exceptions.InvalidHandshake[source]¶
Raised during the handshake when the WebSocket connection fails.
- 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.InvalidMessage[source]¶
Raised when a handshake request or response is malformed.
- exception websockets.exceptions.InvalidOrigin(origin)[source]¶
Raised when the Origin header in a request isn’t allowed.
- 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.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.InvalidStatusCode(status_code)[source]¶
Raised when a handshake response status code is invalid.
The integer status code is available in the
status_codeattribute.
- exception websockets.exceptions.InvalidURI(uri)[source]¶
Raised when connecting to an URI that isn’t a valid WebSocket URI.
- exception websockets.exceptions.InvalidUpgrade(name, value=None)[source]¶
Raised when the Upgrade or Connection header isn’t correct.
- exception websockets.exceptions.NegotiationError[source]¶
Raised when negotiating an extension fails.
- 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.
- exception websockets.exceptions.RedirectHandshake(uri)[source]¶
Raised when a handshake gets redirected.
This exception is an implementation detail.
- exception websockets.exceptions.SecurityError[source]¶
Raised when a handshake request or response breaks a security rule.
Security limits are hard coded.
- exception websockets.exceptions.WebSocketException[source]¶
Base class for all exceptions defined by
websockets.
- websockets.exceptions.WebSocketProtocolError¶
alias of
ProtocolError
Low-level¶
Opening handshake¶
websockets.handshake provides helpers for the WebSocket handshake.
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:
- Returns:
keywhich must be passed tocheck_response()
- websockets.handshake.build_response(headers, key)[source]¶
Build a handshake response to send to the client.
Update response headers passed in argument.
- Parameters:
headers (
Headers) – response headerskey (
str) – comes fromcheck_request()
- Return type:
- 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
HostandOriginchecks. 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:
- Returns:
keywhich must be passed tobuild_response()- Raises:
InvalidHandshake – if the handshake request is invalid; then the server must return 400 Bad Request error
- 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:
headers (
Headers) – response headerskey (
str) – comes frombuild_request()
- Raises:
InvalidHandshake – if the handshake response is invalid
- Return type:
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.
- class websockets.framing.Frame(fin: bool, opcode: int, data: bytes, rsv1: bool = False, rsv2: bool = False, rsv3: bool = False)[source]¶
WebSocket frame.
- Parameters:
Only these fields are needed. The MASK bit, payload length and masking-key are handled on the fly by
read()andwrite().- check()[source]¶
Check that reserved bits and opcode have acceptable values.
- Raises:
ProtocolError – if a reserved bit or the opcode is invalid
- Return type:
- property data¶
Alias for field number 2
- property fin¶
Alias for field number 0
- property opcode¶
Alias for field number 1
- 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 reachedmask (
bool) – whether the frame should be masked i.e. whether the read happens on the server sideextensions (
Optional[Sequence[Extension]]) – list of classes with adecode()method that transforms the frame and return a new frame; extensions are applied in reverse order
- Raises:
PayloadTooBig – if the frame exceeds
max_sizeProtocolError – if the frame contains incorrect values
- Return type:
- property rsv1¶
Alias for field number 3
- property rsv2¶
Alias for field number 4
- property rsv3¶
Alias for field number 5
- write(write, *, mask, extensions=None)[source]¶
Write a WebSocket frame.
- Parameters:
- Raises:
ProtocolError – if the frame contains incorrect values
- Return type:
- 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
datais astr, return abytesobject encodingdatain UTF-8.If
datais a bytes-like object, return abytesobject.
- websockets.framing.parse_close(data)[source]¶
Parse the payload from a close frame.
Return
(code, reason).- Raises:
ProtocolError – if data is ill-formed
UnicodeDecodeError – if the reason isn’t valid UTF-8
- Return type:
- 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
datais astr, returnOP_TEXTand abytesobject encodingdatain UTF-8.If
datais a bytes-like object, returnOP_BINARYand a bytes-like object.
- websockets.framing.serialize_close(code, reason)[source]¶
Serialize the payload for a close frame.
This is the reverse of
parse_close().- Return type:
URI parser¶
websockets.uri parses WebSocket URIs.
- class websockets.uri.WebSocketURI(secure: bool, host: str, port: int, resource_name: str, user_info: Optional[Tuple[str, str]])[source]¶
WebSocket URI.
- websockets.uri.parse_uri(uri)[source]¶
Parse and validate a WebSocket URI.
- Raises:
ValueError – if
uriisn’t a valid WebSocket URI.- Return type:
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.build_authorization_basic(username, password)[source]¶
Build an
Authorizationheader for HTTP Basic Auth.This is the reverse of
parse_authorization_basic().- Return type:
- websockets.headers.build_extension(extensions)[source]¶
Build a
Sec-WebSocket-Extensionsheader.This is the reverse of
parse_extension().- Return type:
- websockets.headers.build_subprotocol(protocols)[source]¶
Build a
Sec-WebSocket-Protocolheader.This is the reverse of
parse_subprotocol().- Return type:
- websockets.headers.build_www_authenticate_basic(realm)[source]¶
Build a
WWW-Authenticateheader for HTTP Basic Auth.
- websockets.headers.parse_authorization_basic(header)[source]¶
Parse an
Authorizationheader for HTTP Basic Auth.Return a
(username, password)tuple.- Parameters:
header (
str) – value of theAuthorizationheader- Raises:
InvalidHeaderFormat – on invalid inputs
InvalidHeaderValue – on unsupported inputs
- Return type:
- websockets.headers.parse_connection(header)[source]¶
Parse a
Connectionheader.Return a list of HTTP connection options.
- Parameters:
header (
str) – value of theConnectionheader- Raises:
InvalidHeaderFormat – on invalid inputs.
- Return type:
- websockets.headers.parse_extension(header)[source]¶
Parse a
Sec-WebSocket-Extensionsheader.Return a list of WebSocket extensions and their parameters in this format:
[ ( 'extension name', [ ('parameter name', 'parameter value'), .... ] ), ... ]
Parameter values are
Nonewhen no value is provided.
- websockets.headers.parse_subprotocol(header)[source]¶
Parse a
Sec-WebSocket-Protocolheader.Return a list of WebSocket subprotocols.
- Raises:
InvalidHeaderFormat – on invalid inputs.
- Return type:
- websockets.headers.parse_upgrade(header)[source]¶
Parse an
Upgradeheader.Return a list of HTTP protocols.
- Parameters:
header (
str) – value of theUpgradeheader- Raises:
InvalidHeaderFormat – on invalid inputs.
- Return type:
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.
- class websockets.http.Headers(*args, **kwargs)[source]¶
Efficient data structure for manipulating HTTP headers.
A
listof(name, values)is inefficient for lookups.A
dictdoesn’t suffice because header names are case-insensitive and multiple occurrences of headers with the same name are possible.Headersstores 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,
Headersfollows this logic:- When getting a header with
headers[name]: if there’s no value,
KeyErroris raised;if there’s exactly one value, it’s returned;
if there’s more than one value,
MultipleValuesErroris raised.
- When getting a header with
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,
Headersbehaves likedict, 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.
- exception websockets.http.MultipleValuesError[source]¶
Exception raised when
Headershas more than one value for a key.
- await websockets.http.read_request(stream)[source]¶
Read an HTTP/1.1 GET request and return
(path, headers).pathisn’t URL-decoded or validated in any way.pathandheadersare 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 fromstreamafter 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:
- await websockets.http.read_response(stream)[source]¶
Read an HTTP/1.1 response and return
(status_code, reason, headers).reasonandheadersare 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 fromstreamafter 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: