websockets API Reference
Full documentation for websockets (15.0.1)
websockets.AbortHandshake
Python Library Documentation: class AbortHandshake in module websockets.legacy.exceptions class AbortHandshake(websockets.exceptions.InvalidHandshake) | AbortHandshake(status: Union[http.HTTPStatus, int], headers: Union[websockets.datastructures.Headers, collections.abc.Mapping[str, str], collections.abc.Iterable[tuple[str, str]], websockets.datastructures.SupportsKeysAndGetItem], body: bytes = b'') -> None | | Raised to abort the handshake on purpose and return an HTTP response. | | This exception is an implementation detail. | | The public API is | :meth:`~websockets.legacy.server.WebSocketServerProtocol.process_request`. | | Attributes: | status (~http.HTTPStatus): HTTP status code. | headers (Headers): HTTP response headers. | body (bytes): HTTP response body. | | Method resolution order: | AbortHandshake | websockets.exceptions.InvalidHandshake | websockets.exceptions.WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, status: Union[http.HTTPStatus, int], headers: Union[websockets.datastructures.Headers, collections.abc.Mapping[str, str], collections.abc.Iterable[tuple[str, str]], websockets.datastructures.SupportsKeysAndGetItem], body: bytes = b'') -> None | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> str | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from websockets.exceptions.WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.BasicAuthWebSocketServerProtocol
Python Library Documentation: class BasicAuthWebSocketServerProtocol in module websockets.legacy.auth
class BasicAuthWebSocketServerProtocol(websockets.legacy.server.WebSocketServerProtocol)
| BasicAuthWebSocketServerProtocol(*args: 'Any', realm: 'str | None' = None, check_credentials: 'Callable[[str, str], Awaitable[bool]] | None' = None, **kwargs: 'Any') -> 'None'
|
| WebSocket server protocol that enforces HTTP Basic Auth.
|
| Method resolution order:
| BasicAuthWebSocketServerProtocol
| websockets.legacy.server.WebSocketServerProtocol
| websockets.legacy.protocol.WebSocketCommonProtocol
| asyncio.protocols.Protocol
| asyncio.protocols.BaseProtocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, *args: 'Any', realm: 'str | None' = None, check_credentials: 'Callable[[str, str], Awaitable[bool]] | None' = None, **kwargs: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| async check_credentials(self, username: 'str', password: 'str') -> 'bool'
| Check whether credentials are authorized.
|
| This coroutine may be overridden in a subclass, for example to
| authenticate against a database or an external service.
|
| Args:
| username: HTTP Basic Auth username.
| password: HTTP Basic Auth password.
|
| Returns:
| :obj:`True` if the handshake should continue;
| :obj:`False` if it should fail with an HTTP 401 error.
|
| async process_request(self, path: 'str', request_headers: 'Headers') -> 'HTTPResponse | None'
| Check HTTP Basic Auth and return an HTTP 401 response if needed.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'realm': 'str', 'username': 'str | None'}
|
| realm = ''
|
| username = None
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.legacy.server.WebSocketServerProtocol:
|
| connection_made(self, transport: 'asyncio.BaseTransport') -> 'None'
| Register connection and initialize a task to handle it.
|
| async handler(self) -> 'None'
| Handle the lifecycle of a WebSocket connection.
|
| Since this method doesn't have a caller able to handle exceptions, it
| attempts to log relevant ones and guarantees that the TCP connection is
| closed before exiting.
|
| async handshake(self, origins: 'Sequence[Origin | None] | None' = None, available_extensions: 'Sequence[ServerExtensionFactory] | None' = None, available_subprotocols: 'Sequence[Subprotocol] | None' = None, extra_headers: 'HeadersLikeOrCallable | None' = None) -> 'str'
| Perform the server side of the opening handshake.
|
| Args:
| origins: List of acceptable values of the Origin HTTP header;
| include :obj:`None` if the lack of an origin is acceptable.
| extensions: List of supported extensions, in order in which they
| should be tried.
| subprotocols: List of supported subprotocols, in order of
| decreasing preference.
| extra_headers: Arbitrary HTTP headers to add to the response when
| the handshake succeeds.
|
| Returns:
| path of the URI of the request.
|
| Raises:
| InvalidHandshake: If the handshake fails.
|
| process_subprotocol(self, headers: 'Headers', available_subprotocols: 'Sequence[Subprotocol] | None') -> 'Subprotocol | None'
| Handle the Sec-WebSocket-Protocol HTTP request header.
|
| Return Sec-WebSocket-Protocol HTTP response header, which is the same
| as the selected subprotocol.
|
| Args:
| headers: Request headers.
| available_subprotocols: Optional list of supported subprotocols.
|
| Raises:
| InvalidHandshake: To abort the handshake with an HTTP 400 error.
|
| async read_http_request(self) -> 'tuple[str, Headers]'
| Read request line and headers from the HTTP request.
|
| If the request contains a body, it may be read from ``self.reader``
| after this coroutine returns.
|
| Raises:
| InvalidMessage: If the HTTP message is malformed or isn't an
| HTTP/1.1 GET request.
|
| select_subprotocol(self, client_subprotocols: 'Sequence[Subprotocol]', server_subprotocols: 'Sequence[Subprotocol]') -> 'Subprotocol | None'
| Pick a subprotocol among those supported by the client and the server.
|
| If several subprotocols are available, select the preferred subprotocol
| by giving equal weight to the preferences of the client and the server.
|
| If no subprotocol is available, proceed without a subprotocol.
|
| You may provide a ``select_subprotocol`` argument to :func:`serve` or
| :class:`WebSocketServerProtocol` to override this logic. For example,
| you could reject the handshake if the client doesn't support a
| particular subprotocol, rather than accept the handshake without that
| subprotocol.
|
| Args:
| client_subprotocols: List of subprotocols offered by the client.
| server_subprotocols: List of subprotocols available on the server.
|
| Returns:
| Selected subprotocol, if a common subprotocol was found.
|
| :obj:`None` to continue without a subprotocol.
|
| write_http_response(self, status: 'http.HTTPStatus', headers: 'Headers', body: 'bytes | None' = None) -> 'None'
| Write status line and headers to the HTTP response.
|
| This coroutine is also able to write a response body.
|
| ----------------------------------------------------------------------
| Static methods inherited from websockets.legacy.server.WebSocketServerProtocol:
|
| process_extensions(headers: 'Headers', available_extensions: 'Sequence[ServerExtensionFactory] | None') -> 'tuple[str | None, list[Extension]]'
| Handle the Sec-WebSocket-Extensions HTTP request header.
|
| Accept or reject each extension proposed in the client request.
| Negotiate parameters for accepted extensions.
|
| Return the Sec-WebSocket-Extensions HTTP response header and the list
| of accepted extensions.
|
| :rfc:`6455` leaves the rules up to the specification of each
| :extension.
|
| To provide this level of flexibility, for each extension proposed by
| the client, we check for a match with each extension available in the
| server configuration. If no match is found, the extension is ignored.
|
| If several variants of the same extension are proposed by the client,
| it may be accepted several times, which won't make sense in general.
| Extensions must implement their own requirements. For this purpose,
| the list of previously accepted extensions is provided.
|
| This process doesn't allow the server to reorder extensions. It can
| only select a subset of the extensions proposed by the client.
|
| Other requirements, for example related to mandatory extensions or the
| order of extensions, may be implemented by overriding this method.
|
| Args:
| headers: Request headers.
| extensions: Optional list of supported extensions.
|
| Raises:
| InvalidHandshake: To abort the handshake with an HTTP 400 error.
|
| process_origin(headers: 'Headers', origins: 'Sequence[Origin | None] | None' = None) -> 'Origin | None'
| Handle the Origin HTTP request header.
|
| Args:
| headers: Request headers.
| origins: Optional list of acceptable origins.
|
| Raises:
| InvalidOrigin: If the origin isn't acceptable.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from websockets.legacy.server.WebSocketServerProtocol:
|
| is_client = False
|
| side = 'server'
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| async __aiter__(self) -> 'AsyncIterator[Data]'
| Iterate on incoming messages.
|
| The iterator exits normally when the connection is closed with the close
| code 1000 (OK) or 1001 (going away) or without a close code.
|
| It raises a :exc:`~websockets.exceptions.ConnectionClosedError`
| exception when the connection is closed with any other code.
|
| abort_pings(self) -> 'None'
| Raise ConnectionClosed in pending keepalive pings.
|
| They'll never receive a pong once the connection is closed.
|
| async close(self, code: 'int' = <CloseCode.NORMAL_CLOSURE: 1000>, reason: 'str' = '') -> 'None'
| Perform the closing handshake.
|
| :meth:`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 :meth:`wait_closed` after :meth:`close`.
|
| :meth:`close` is idempotent: it doesn't do anything once the
| connection is closed.
|
| Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given
| that errors during connection termination aren't particularly useful.
|
| Canceling :meth:`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 take care of closing the TCP
| connection.
|
| Args:
| code: WebSocket close code.
| reason: WebSocket close reason.
|
| async close_connection(self) -> 'None'
| 7.1.1. Close the WebSocket Connection
|
| When the opening handshake succeeds, :meth:`connection_open` starts
| this coroutine in a task. It waits for the data transfer phase to
| complete then it closes the TCP connection cleanly.
|
| When the opening handshake fails, :meth:`fail_connection` does the
| same. There's no data transfer phase in that case.
|
| async close_transport(self) -> 'None'
| Close the TCP connection.
|
| connection_closed_exc(self) -> 'ConnectionClosed'
|
| connection_lost(self, exc: 'Exception | None') -> 'None'
| 7.1.4. The WebSocket Connection is Closed.
|
| connection_open(self) -> 'None'
| Callback when the WebSocket opening handshake completes.
|
| Enter the OPEN state and start the data transfer phase.
|
| data_received(self, data: 'bytes') -> 'None'
| Called when some data is received.
|
| The argument is a bytes object.
|
| async drain(self) -> 'None'
|
| async ensure_open(self) -> 'None'
| Check that the WebSocket connection is open.
|
| Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.
|
| eof_received(self) -> 'None'
| Close the transport after receiving EOF.
|
| The WebSocket protocol has its own closing handshake: endpoints close
| the TCP or TLS connection after sending and receiving a close frame.
|
| As a consequence, they never need to write after receiving EOF, so
| there's no reason to keep the transport open by returning :obj:`True`.
|
| Besides, that doesn't work on TLS connections.
|
| fail_connection(self, code: 'int' = <CloseCode.ABNORMAL_CLOSURE: 1006>, reason: 'str' = '') -> 'None'
| 7.1.7. Fail the WebSocket Connection
|
| This requires:
|
| 1. Stopping all processing of incoming data, which means cancelling
| :attr:`transfer_data_task`. The close code will be 1006 unless a
| close frame was received earlier.
|
| 2. Sending a close frame with an appropriate code if the opening
| handshake succeeded and the other side is likely to process it.
|
| 3. Closing the connection. :meth:`close_connection` takes care of
| this once :attr:`transfer_data_task` exits after being canceled.
|
| (The specification describes these steps in the opposite order.)
|
| async keepalive_ping(self) -> 'None'
| Send a Ping frame and wait for a Pong frame at regular intervals.
|
| This coroutine exits when the connection terminates and one of the
| following happens:
|
| - :meth:`ping` raises :exc:`ConnectionClosed`, or
| - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.
|
| pause_writing(self) -> 'None'
| Called when the transport's buffer goes over the high-water mark.
|
| Pause and resume calls are paired -- pause_writing() is called
| once when the buffer goes strictly over the high-water mark
| (even if subsequent writes increases the buffer size even
| more), and eventually resume_writing() is called once when the
| buffer size reaches the low-water mark.
|
| Note that if the buffer size equals the high-water mark,
| pause_writing() is not called -- it must go strictly over.
| Conversely, resume_writing() is called when the buffer size is
| equal or lower than the low-water mark. These end conditions
| are important to ensure that things go as expected when either
| mark is zero.
|
| NOTE: This is the only Protocol callback that is not called
| through EventLoop.call_soon() -- if it were, it would have no
| effect when it's most needed (when the app keeps writing
| without yielding until pause_writing() is called).
|
| async ping(self, data: 'Data | None' = None) -> 'Awaitable[float]'
| Send a Ping_.
|
| .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| A ping may serve as a keepalive, as a check that the remote endpoint
| received all messages up to this point, or to measure :attr:`latency`.
|
| Canceling :meth:`ping` is discouraged. If :meth:`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 :class:`~asyncio.Future` returned by :meth:`ping` has no
| effect.
|
| Args:
| data: Payload of the ping. A string will be encoded to UTF-8.
| If ``data`` is :obj:`None`, the payload is four random bytes.
|
| Returns:
| A future that will be completed when the corresponding pong is
| received. You can ignore it if you don't intend to wait. The result
| of the future is the latency of the connection in seconds.
|
| ::
|
| pong_waiter = await ws.ping()
| # only if you want to wait for the corresponding pong
| latency = await pong_waiter
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If another ping was sent with the same data and
| the corresponding pong wasn't received yet.
|
| async pong(self, data: 'Data' = b'') -> 'None'
| Send a Pong_.
|
| .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| An unsolicited pong may serve as a unidirectional heartbeat.
|
| Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return
| immediately, it means the write buffer is full. If you don't want to
| wait, you should close the connection.
|
| Args:
| data: Payload of the pong. A string will be encoded to UTF-8.
|
| Raises:
| ConnectionClosed: When the connection is closed.
|
| async read_data_frame(self, max_size: 'int | None') -> 'Frame | None'
| Read a single data frame from the connection.
|
| Process control frames received before the next data frame.
|
| Return :obj:`None` if a close frame is encountered before any data frame.
|
| async read_frame(self, max_size: 'int | None') -> 'Frame'
| Read a single frame from the connection.
|
| async read_message(self) -> 'Data | None'
| Read a single message from the connection.
|
| Re-assemble data frames if the message is fragmented.
|
| Return :obj:`None` when the closing handshake is started.
|
| async recv(self) -> 'Data'
| Receive the next message.
|
| When the connection is closed, :meth:`recv` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
| :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure. This is how you detect the end of the
| message stream.
|
| Canceling :meth:`recv` is safe. There's no risk of losing the next
| message. The next invocation of :meth:`recv` will return it.
|
| This makes it possible to enforce a timeout by wrapping :meth:`recv` in
| :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
|
| Returns:
| A string (:class:`str`) for a Text_ frame. A bytestring
| (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If two coroutines call :meth:`recv` concurrently.
|
| resume_writing(self) -> 'None'
| Called when the transport's buffer drains below the low-water mark.
|
| See pause_writing() for details.
|
| async send(self, message: 'Data | Iterable[Data] | AsyncIterable[Data]') -> 'None'
| Send a message.
|
| A string (:class:`str`) is sent as a Text_ frame. A bytestring or
| bytes-like object (:class:`bytes`, :class:`bytearray`, or
| :class:`memoryview`) is sent as a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| :meth:`send` also accepts an iterable or an asynchronous iterable of
| strings, bytestrings, or bytes-like objects to enable fragmentation_.
| Each item is treated as a message fragment and sent in its own frame.
| All items must be of the same type, or else :meth:`send` will raise a
| :exc:`TypeError` and the connection will be closed.
|
| .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
|
| :meth:`send` rejects dict-like objects because this is often an error.
| (If you want to send the keys of a dict-like object as fragments, call
| its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
|
| Canceling :meth:`send` is discouraged. Instead, you should close the
| connection with :meth:`close`. Indeed, there are only two situations
| where :meth:`send` may yield control to the event loop and then get
| canceled; in both cases, :meth:`close` has the same effect and is
| more clear:
|
| 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.
| :meth:`close` will likely time out then abort the TCP connection.
| 2. ``message`` is an asynchronous iterator that yields control.
| Stopping in the middle of a fragmented message will cause a
| protocol error and the connection will be closed.
|
| When the connection is closed, :meth:`send` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
| raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure.
|
| Args:
| message: Message to send.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| TypeError: If ``message`` doesn't have a supported type.
|
| async transfer_data(self) -> 'None'
| Read incoming messages and put them in a queue.
|
| This coroutine runs in a task until the closing handshake is started.
|
| async wait_closed(self) -> 'None'
| Wait until the connection is closed.
|
| This coroutine is identical to the :attr:`closed` attribute, except it
| can be awaited.
|
| This can make it easier to detect connection termination, regardless
| of its cause, in tasks that interact with the WebSocket connection.
|
| async wait_for_connection_lost(self) -> 'bool'
| Wait until the TCP connection is closed or ``self.close_timeout`` elapses.
|
| Return :obj:`True` if the connection is closed and :obj:`False`
| otherwise.
|
| async write_close_frame(self, close: 'Close', data: 'bytes | None' = None) -> 'None'
| Write a close frame if and only if the connection state is OPEN.
|
| This dedicated coroutine must be used for writing close frames to
| ensure that at most one close frame is sent on a given connection.
|
| async write_frame(self, fin: 'bool', opcode: 'int', data: 'bytes', *, _state: 'int' = <State.OPEN: 1>) -> 'None'
|
| write_frame_sync(self, fin: 'bool', opcode: 'int', data: 'bytes') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| close_code
| WebSocket close code, defined in `section 7.1.5 of RFC 6455`_.
|
| .. _section 7.1.5 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
|
| :obj:`None` if the connection isn't closed yet.
|
| close_reason
| WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_.
|
| .. _section 7.1.6 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
|
| :obj:`None` if the connection isn't closed yet.
|
| closed
| :obj:`True` when the connection is closed; :obj:`False` otherwise.
|
| Be aware that both :attr:`open` and :attr:`closed` are :obj:`False`
| during the opening and closing sequences.
|
| host
|
| local_address
| Local address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getsockname`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| open
| :obj:`True` when the connection is open; :obj:`False` otherwise.
|
| This attribute may be used to detect disconnections. However, this
| approach is discouraged per the EAFP_ principle. Instead, you should
| handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp
|
| port
|
| remote_address
| Remote address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getpeername`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| secure
|
| ----------------------------------------------------------------------
| Data descriptors inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.ClientConnection
Python Library Documentation: class ClientConnection in module websockets.asyncio.client
class ClientConnection(websockets.asyncio.connection.Connection)
| ClientConnection(protocol: 'ClientProtocol', *, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768) -> 'None'
|
| :mod:`asyncio` implementation of a WebSocket client connection.
|
| :class:`ClientConnection` provides :meth:`recv` and :meth:`send` coroutines
| for receiving and sending messages.
|
| It supports asynchronous iteration to receive messages::
|
| async for message in websocket:
| await process(message)
|
| The iterator exits normally when the connection is closed with close code
| 1000 (OK) or 1001 (going away) or without a close code. It raises a
| :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
| closed with any other code.
|
| The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``,
| and ``write_limit`` arguments have the same meaning as in :func:`connect`.
|
| Args:
| protocol: Sans-I/O connection.
|
| Method resolution order:
| ClientConnection
| websockets.asyncio.connection.Connection
| asyncio.protocols.Protocol
| asyncio.protocols.BaseProtocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, protocol: 'ClientProtocol', *, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| async handshake(self, additional_headers: 'HeadersLike | None' = None, user_agent_header: 'str | None' = 'Python/3.12 websockets/15.0.1') -> 'None'
| Perform the opening handshake.
|
| process_event(self, event: 'Event') -> 'None'
| Process one incoming event.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.asyncio.connection.Connection:
|
| async __aenter__(self) -> 'Connection'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
|
| async __aiter__(self) -> 'AsyncIterator[Data]'
| Iterate on incoming messages.
|
| The iterator calls :meth:`recv` and yields messages asynchronously in an
| infinite loop.
|
| It exits when the connection is closed normally. It raises a
| :exc:`~websockets.exceptions.ConnectionClosedError` exception after a
| protocol error or a network failure.
|
| abort_pings(self) -> 'None'
| Raise ConnectionClosed in pending pings.
|
| They'll never receive a pong once the connection is closed.
|
| acknowledge_pings(self, data: 'bytes') -> 'None'
| Acknowledge pings when receiving a pong.
|
| async close(self, code: 'int' = 1000, reason: 'str' = '') -> 'None'
| Perform the closing handshake.
|
| :meth:`close` waits for the other end to complete the handshake and
| for the TCP connection to terminate.
|
| :meth:`close` is idempotent: it doesn't do anything once the
| connection is closed.
|
| Args:
| code: WebSocket close code.
| reason: WebSocket close reason.
|
| connection_lost(self, exc: 'Exception | None') -> 'None'
| Called when the connection is lost or closed.
|
| The argument is an exception object or None (the latter
| meaning a regular EOF is received or the connection was
| aborted or closed).
|
| connection_made(self, transport: 'asyncio.BaseTransport') -> 'None'
| Called when a connection is made.
|
| The argument is the transport representing the pipe connection.
| To receive data, wait for data_received() calls.
| When the connection is closed, connection_lost() is called.
|
| data_received(self, data: 'bytes') -> 'None'
| Called when some data is received.
|
| The argument is a bytes object.
|
| async drain(self) -> 'None'
|
| eof_received(self) -> 'None'
| Called when the other end calls write_eof() or equivalent.
|
| If this returns a false value (including None), the transport
| will close itself. If it returns a true value, closing the
| transport is up to the protocol.
|
| async keepalive(self) -> 'None'
| Send a Ping frame and wait for a Pong frame at regular intervals.
|
| pause_writing(self) -> 'None'
| Called when the transport's buffer goes over the high-water mark.
|
| Pause and resume calls are paired -- pause_writing() is called
| once when the buffer goes strictly over the high-water mark
| (even if subsequent writes increases the buffer size even
| more), and eventually resume_writing() is called once when the
| buffer size reaches the low-water mark.
|
| Note that if the buffer size equals the high-water mark,
| pause_writing() is not called -- it must go strictly over.
| Conversely, resume_writing() is called when the buffer size is
| equal or lower than the low-water mark. These end conditions
| are important to ensure that things go as expected when either
| mark is zero.
|
| NOTE: This is the only Protocol callback that is not called
| through EventLoop.call_soon() -- if it were, it would have no
| effect when it's most needed (when the app keeps writing
| without yielding until pause_writing() is called).
|
| async ping(self, data: 'Data | None' = None) -> 'Awaitable[float]'
| Send a Ping_.
|
| .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| A ping may serve as a keepalive or as a check that the remote endpoint
| received all messages up to this point
|
| Args:
| data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
| If ``data`` is :obj:`None`, the payload is four random bytes.
|
| Returns:
| A future that will be completed when the corresponding pong is
| received. You can ignore it if you don't intend to wait. The result
| of the future is the latency of the connection in seconds.
|
| ::
|
| pong_waiter = await ws.ping()
| # only if you want to wait for the corresponding pong
| latency = await pong_waiter
|
| Raises:
| ConnectionClosed: When the connection is closed.
| ConcurrencyError: If another ping was sent with the same data and
| the corresponding pong wasn't received yet.
|
| async pong(self, data: 'Data' = b'') -> 'None'
| Send a Pong_.
|
| .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| An unsolicited pong may serve as a unidirectional heartbeat.
|
| Args:
| data: Payload of the pong. A :class:`str` will be encoded to UTF-8.
|
| Raises:
| ConnectionClosed: When the connection is closed.
|
| async recv(self, decode: 'bool | None' = None) -> 'Data'
| Receive the next message.
|
| When the connection is closed, :meth:`recv` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
| :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure
| and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure. This is how you detect the end of the
| message stream.
|
| Canceling :meth:`recv` is safe. There's no risk of losing data. The next
| invocation of :meth:`recv` will return the next message.
|
| This makes it possible to enforce a timeout by wrapping :meth:`recv` in
| :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
|
| When the message is fragmented, :meth:`recv` waits until all fragments
| are received, reassembles them, and returns the whole message.
|
| Args:
| decode: Set this flag to override the default behavior of returning
| :class:`str` or :class:`bytes`. See below for details.
|
| Returns:
| A string (:class:`str`) for a Text_ frame or a bytestring
| (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| You may override this behavior with the ``decode`` argument:
|
| * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
| return a bytestring (:class:`bytes`). This improves performance
| when decoding isn't needed, for example if the message contains
| JSON and you're using a JSON library that expects a bytestring.
| * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames
| and return a string (:class:`str`). This may be useful for
| servers that send binary frames instead of text frames.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| ConcurrencyError: If two coroutines call :meth:`recv` or
| :meth:`recv_streaming` concurrently.
|
| async recv_streaming(self, decode: 'bool | None' = None) -> 'AsyncIterator[Data]'
| Receive the next message frame by frame.
|
| This method is designed for receiving fragmented messages. It returns an
| asynchronous iterator that yields each fragment as it is received. This
| iterator must be fully consumed. Else, future calls to :meth:`recv` or
| :meth:`recv_streaming` will raise
| :exc:`~websockets.exceptions.ConcurrencyError`, making the connection
| unusable.
|
| :meth:`recv_streaming` raises the same exceptions as :meth:`recv`.
|
| Canceling :meth:`recv_streaming` before receiving the first frame is
| safe. Canceling it after receiving one or more frames leaves the
| iterator in a partially consumed state, making the connection unusable.
| Instead, you should close the connection with :meth:`close`.
|
| Args:
| decode: Set this flag to override the default behavior of returning
| :class:`str` or :class:`bytes`. See below for details.
|
| Returns:
| An iterator of strings (:class:`str`) for a Text_ frame or
| bytestrings (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| You may override this behavior with the ``decode`` argument:
|
| * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames
| and return bytestrings (:class:`bytes`). This may be useful to
| optimize performance when decoding isn't needed.
| * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames
| and return strings (:class:`str`). This is useful for servers
| that send binary frames instead of text frames.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| ConcurrencyError: If two coroutines call :meth:`recv` or
| :meth:`recv_streaming` concurrently.
|
| resume_writing(self) -> 'None'
| Called when the transport's buffer drains below the low-water mark.
|
| See pause_writing() for details.
|
| async send(self, message: 'Data | Iterable[Data] | AsyncIterable[Data]', text: 'bool | None' = None) -> 'None'
| Send a message.
|
| A string (:class:`str`) is sent as a Text_ frame. A bytestring or
| bytes-like object (:class:`bytes`, :class:`bytearray`, or
| :class:`memoryview`) is sent as a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| You may override this behavior with the ``text`` argument:
|
| * Set ``text=True`` to send a bytestring or bytes-like object
| (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a
| Text_ frame. This improves performance when the message is already
| UTF-8 encoded, for example if the message contains JSON and you're
| using a JSON library that produces a bytestring.
| * Set ``text=False`` to send a string (:class:`str`) in a Binary_
| frame. This may be useful for servers that expect binary frames
| instead of text frames.
|
| :meth:`send` also accepts an iterable or an asynchronous iterable of
| strings, bytestrings, or bytes-like objects to enable fragmentation_.
| Each item is treated as a message fragment and sent in its own frame.
| All items must be of the same type, or else :meth:`send` will raise a
| :exc:`TypeError` and the connection will be closed.
|
| .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
|
| :meth:`send` rejects dict-like objects because this is often an error.
| (If you really want to send the keys of a dict-like object as fragments,
| call its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
|
| Canceling :meth:`send` is discouraged. Instead, you should close the
| connection with :meth:`close`. Indeed, there are only two situations
| where :meth:`send` may yield control to the event loop and then get
| canceled; in both cases, :meth:`close` has the same effect and is
| more clear:
|
| 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.
| :meth:`close` will likely time out then abort the TCP connection.
| 2. ``message`` is an asynchronous iterator that yields control.
| Stopping in the middle of a fragmented message will cause a
| protocol error and the connection will be closed.
|
| When the connection is closed, :meth:`send` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
| raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure.
|
| Args:
| message: Message to send.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| TypeError: If ``message`` doesn't have a supported type.
|
| send_context(self, *, expected_state: 'State' = <State.OPEN: 1>) -> 'AsyncIterator[None]'
| Create a context for writing to the connection from user code.
|
| On entry, :meth:`send_context` checks that the connection is open; on
| exit, it writes outgoing data to the socket::
|
| async with self.send_context():
| self.protocol.send_text(message.encode())
|
| When the connection isn't open on entry, when the connection is expected
| to close on exit, or when an unexpected error happens, terminating the
| connection, :meth:`send_context` waits until the connection is closed
| then raises :exc:`~websockets.exceptions.ConnectionClosed`.
|
| send_data(self) -> 'None'
| Send outgoing data.
|
| Raises:
| OSError: When a socket operations fails.
|
| set_recv_exc(self, exc: 'BaseException | None') -> 'None'
| Set recv_exc, if not set yet.
|
| start_keepalive(self) -> 'None'
| Run :meth:`keepalive` in a task, unless keepalive is disabled.
|
| async wait_closed(self) -> 'None'
| Wait until the connection is closed.
|
| :meth:`wait_closed` waits for the closing handshake to complete and for
| the TCP connection to terminate.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from websockets.asyncio.connection.Connection:
|
| close_code
| State of the WebSocket connection, defined in :rfc:`6455`.
|
| This attribute is provided for completeness. Typical applications
| shouldn't check its value. Instead, they should inspect attributes
| of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| close_reason
| State of the WebSocket connection, defined in :rfc:`6455`.
|
| This attribute is provided for completeness. Typical applications
| shouldn't check its value. Instead, they should inspect attributes
| of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| local_address
| Local address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family.
| See :meth:`~socket.socket.getsockname`.
|
| remote_address
| Remote address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family.
| See :meth:`~socket.socket.getpeername`.
|
| state
| State of the WebSocket connection, defined in :rfc:`6455`.
|
| This attribute is provided for completeness. Typical applications
| shouldn't check its value. Instead, they should call :meth:`~recv` or
| :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed`
| exceptions.
|
| subprotocol
| Subprotocol negotiated during the opening handshake.
|
| :obj:`None` if no subprotocol was negotiated.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from websockets.asyncio.connection.Connection:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.ClientProtocol
Python Library Documentation: class ClientProtocol in module websockets.client
class ClientProtocol(websockets.protocol.Protocol)
| ClientProtocol(uri: 'WebSocketURI', *, origin: 'Origin | None' = None, extensions: 'Sequence[ClientExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, state: 'State' = <State.CONNECTING: 0>, max_size: 'int | None' = 1048576, logger: 'LoggerLike | None' = None) -> 'None'
|
| Sans-I/O implementation of a WebSocket client connection.
|
| Args:
| uri: URI of the WebSocket server, parsed
| with :func:`~websockets.uri.parse_uri`.
| origin: Value of the ``Origin`` header. This is useful when connecting
| to a server that validates the ``Origin`` header to defend against
| Cross-Site WebSocket Hijacking attacks.
| extensions: List of supported extensions, in order in which they
| should be tried.
| subprotocols: List of supported subprotocols, in order of decreasing
| preference.
| state: Initial state of the WebSocket connection.
| max_size: Maximum size of incoming messages in bytes;
| :obj:`None` disables the limit.
| logger: Logger for this connection;
| defaults to ``logging.getLogger("websockets.client")``;
| see the :doc:`logging guide <../../topics/logging>` for details.
|
| Method resolution order:
| ClientProtocol
| websockets.protocol.Protocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, uri: 'WebSocketURI', *, origin: 'Origin | None' = None, extensions: 'Sequence[ClientExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, state: 'State' = <State.CONNECTING: 0>, max_size: 'int | None' = 1048576, logger: 'LoggerLike | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| connect(self) -> 'Request'
| Create a handshake request to open a connection.
|
| You must send the handshake request with :meth:`send_request`.
|
| You can modify it before sending it, for example to add HTTP headers.
|
| Returns:
| WebSocket handshake request event to send to the server.
|
| parse(self) -> 'Generator[None]'
| Parse incoming data into frames.
|
| :meth:`receive_data` and :meth:`receive_eof` run this generator
| coroutine until it needs more data or reaches EOF.
|
| :meth:`parse` never raises an exception. Instead, it sets the
| :attr:`parser_exc` and yields control.
|
| process_extensions(self, headers: 'Headers') -> 'list[Extension]'
| Handle the Sec-WebSocket-Extensions HTTP response header.
|
| Check that each extension is supported, as well as its parameters.
|
| :rfc:`6455` leaves the rules up to the specification of each
| extension.
|
| To provide this level of flexibility, for each extension accepted by
| the server, we check for a match with each extension available in the
| client configuration. If no match is found, an exception is raised.
|
| If several variants of the same extension are accepted by the server,
| it may be configured several times, which won't make sense in general.
| Extensions must implement their own requirements. For this purpose,
| the list of previously accepted extensions is provided.
|
| Other requirements, for example related to mandatory extensions or the
| order of extensions, may be implemented by overriding this method.
|
| Args:
| headers: WebSocket handshake response headers.
|
| Returns:
| List of accepted extensions.
|
| Raises:
| InvalidHandshake: To abort the handshake.
|
| process_response(self, response: 'Response') -> 'None'
| Check a handshake response.
|
| Args:
| request: WebSocket handshake response received from the server.
|
| Raises:
| InvalidHandshake: If the handshake response is invalid.
|
| process_subprotocol(self, headers: 'Headers') -> 'Subprotocol | None'
| Handle the Sec-WebSocket-Protocol HTTP response header.
|
| If provided, check that it contains exactly one supported subprotocol.
|
| Args:
| headers: WebSocket handshake response headers.
|
| Returns:
| Subprotocol, if one was selected.
|
| send_request(self, request: 'Request') -> 'None'
| Send a handshake request to the server.
|
| Args:
| request: WebSocket handshake request event.
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.protocol.Protocol:
|
| close_expected(self) -> 'bool'
| Tell if the TCP connection is expected to close soon.
|
| Call this method immediately after any of the ``receive_*()``,
| ``send_close()``, or :meth:`fail` methods.
|
| If it returns :obj:`True`, schedule closing the TCP connection after a
| short timeout if the other side hasn't already closed it.
|
| Returns:
| Whether the TCP connection is expected to close soon.
|
| data_to_send(self) -> 'list[bytes]'
| Obtain data to send to the network.
|
| Call this method immediately after any of the ``receive_*()``,
| ``send_*()``, or :meth:`fail` methods.
|
| Write resulting data to the connection.
|
| The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals
| the end of the data stream. When you receive it, half-close the TCP
| connection.
|
| Returns:
| Data to write to the connection.
|
| discard(self) -> 'Generator[None]'
| Discard incoming data.
|
| This coroutine replaces :meth:`parse`:
|
| - after receiving a close frame, during a normal closure (1.4);
| - after sending a close frame, during an abnormal closure (7.1.7).
|
| events_received(self) -> 'list[Event]'
| Fetch events generated from data received from the network.
|
| Call this method immediately after any of the ``receive_*()`` methods.
|
| Process resulting events, likely by passing them to the application.
|
| Returns:
| Events read from the connection.
|
| fail(self, code: 'int', reason: 'str' = '') -> 'None'
| `Fail the WebSocket connection`_.
|
| .. _Fail the WebSocket connection:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7
|
| Parameters:
| code: close code
| reason: close reason
|
| Raises:
| ProtocolError: If the code isn't valid.
|
| receive_data(self, data: 'bytes') -> 'None'
| Receive data from the network.
|
| After calling this method:
|
| - You must call :meth:`data_to_send` and send this data to the network.
| - You should call :meth:`events_received` and process resulting events.
|
| Raises:
| EOFError: If :meth:`receive_eof` was called earlier.
|
| receive_eof(self) -> 'None'
| Receive the end of the data stream from the network.
|
| After calling this method:
|
| - You must call :meth:`data_to_send` and send this data to the network;
| it will return ``[b""]``, signaling the end of the stream, or ``[]``.
| - You aren't expected to call :meth:`events_received`; it won't return
| any new events.
|
| :meth:`receive_eof` is idempotent.
|
| recv_frame(self, frame: 'Frame') -> 'None'
| Process an incoming frame.
|
| send_binary(self, data: 'bytes', fin: 'bool' = True) -> 'None'
| Send a `Binary frame`_.
|
| .. _Binary frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing arbitrary binary data.
| fin: FIN bit; set it to :obj:`False` if this is the first frame of
| a fragmented message.
|
| Raises:
| ProtocolError: If a fragmented message is in progress.
|
| send_close(self, code: 'int | None' = None, reason: 'str' = '') -> 'None'
| Send a `Close frame`_.
|
| .. _Close frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1
|
| Parameters:
| code: close code.
| reason: close reason.
|
| Raises:
| ProtocolError: If the code isn't valid or if a reason is provided
| without a code.
|
| send_continuation(self, data: 'bytes', fin: 'bool') -> 'None'
| Send a `Continuation frame`_.
|
| .. _Continuation frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing the same kind of data
| as the initial frame.
| fin: FIN bit; set it to :obj:`True` if this is the last frame
| of a fragmented message and to :obj:`False` otherwise.
|
| Raises:
| ProtocolError: If a fragmented message isn't in progress.
|
| send_eof(self) -> 'None'
|
| send_frame(self, frame: 'Frame') -> 'None'
|
| send_ping(self, data: 'bytes') -> 'None'
| Send a `Ping frame`_.
|
| .. _Ping frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| Parameters:
| data: payload containing arbitrary binary data.
|
| send_pong(self, data: 'bytes') -> 'None'
| Send a `Pong frame`_.
|
| .. _Pong frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| Parameters:
| data: payload containing arbitrary binary data.
|
| send_text(self, data: 'bytes', fin: 'bool' = True) -> 'None'
| Send a `Text frame`_.
|
| .. _Text frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing text encoded with UTF-8.
| fin: FIN bit; set it to :obj:`False` if this is the first frame of
| a fragmented message.
|
| Raises:
| ProtocolError: If a fragmented message is in progress.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from websockets.protocol.Protocol:
|
| close_code
| WebSocket close code received from the remote endpoint.
|
| Defined in 7.1.5_ of :rfc:`6455`.
|
| .. _7.1.5: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
|
| :obj:`None` if the connection isn't closed yet.
|
| close_exc
| Exception to raise when trying to interact with a closed connection.
|
| Don't raise this exception while the connection :attr:`state`
| is :attr:`~websockets.protocol.State.CLOSING`; wait until
| it's :attr:`~websockets.protocol.State.CLOSED`.
|
| Indeed, the exception includes the close code and reason, which are
| known only once the connection is closed.
|
| Raises:
| AssertionError: If the connection isn't closed yet.
|
| close_reason
| WebSocket close reason received from the remote endpoint.
|
| Defined in 7.1.6_ of :rfc:`6455`.
|
| .. _7.1.6: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
|
| :obj:`None` if the connection isn't closed yet.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from websockets.protocol.Protocol:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| state
| State of the WebSocket connection.
|
| Defined in 4.1_, 4.2_, 7.1.3_, and 7.1.4_ of :rfc:`6455`.
|
| .. _4.1: https://datatracker.ietf.org/doc/html/rfc6455#section-4.1
| .. _4.2: https://datatracker.ietf.org/doc/html/rfc6455#section-4.2
| .. _7.1.3: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.3
| .. _7.1.4: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
websockets.Close
Python Library Documentation: class Close in module websockets.frames
class Close(builtins.object)
| Close(code: 'int', reason: 'str') -> None
|
| Code and reason for WebSocket close frames.
|
| Attributes:
| code: Close code.
| reason: Close reason.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, code: 'int', reason: 'str') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __str__(self) -> 'str'
| Return a human-readable representation of a close code and reason.
|
| check(self) -> 'None'
| Check that the close code has a valid value for a close frame.
|
| Raises:
| ProtocolError: If the close code is invalid.
|
| serialize(self) -> 'bytes'
| Serialize the payload of a close frame.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| parse(data: 'bytes') -> 'Close'
| Parse the payload of a close frame.
|
| Args:
| data: Payload of the close frame.
|
| Raises:
| ProtocolError: If data is ill-formed.
| UnicodeDecodeError: If the reason isn't valid UTF-8.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'code': 'int', 'reason': 'str'}
|
| __dataclass_fields__ = {'code': Field(name='code',type='int',default=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('code', 'reason')
websockets.CloseCode
Python Library Documentation: class CloseCode in module websockets.frames class CloseCode(enum.IntEnum) | CloseCode(*values) | | Close code values for WebSocket close frames. | | Method resolution order: | CloseCode | enum.IntEnum | builtins.int | enum.ReprEnum | enum.Enum | builtins.object | | Methods defined here: | | __format__(self, format_spec, /) from builtins.int | Convert to a string according to format_spec. | | __new__(cls, value) from enum.Enum | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | ABNORMAL_CLOSURE = <CloseCode.ABNORMAL_CLOSURE: 1006> | | BAD_GATEWAY = <CloseCode.BAD_GATEWAY: 1014> | | GOING_AWAY = <CloseCode.GOING_AWAY: 1001> | | INTERNAL_ERROR = <CloseCode.INTERNAL_ERROR: 1011> | | INVALID_DATA = <CloseCode.INVALID_DATA: 1007> | | MANDATORY_EXTENSION = <CloseCode.MANDATORY_EXTENSION: 1010> | | MESSAGE_TOO_BIG = <CloseCode.MESSAGE_TOO_BIG: 1009> | | NORMAL_CLOSURE = <CloseCode.NORMAL_CLOSURE: 1000> | | NO_STATUS_RCVD = <CloseCode.NO_STATUS_RCVD: 1005> | | POLICY_VIOLATION = <CloseCode.POLICY_VIOLATION: 1008> | | PROTOCOL_ERROR = <CloseCode.PROTOCOL_ERROR: 1002> | | SERVICE_RESTART = <CloseCode.SERVICE_RESTART: 1012> | | TLS_HANDSHAKE = <CloseCode.TLS_HANDSHAKE: 1015> | | TRY_AGAIN_LATER = <CloseCode.TRY_AGAIN_LATER: 1013> | | UNSUPPORTED_DATA = <CloseCode.UNSUPPORTED_DATA: 1003> | | ---------------------------------------------------------------------- | Methods inherited from enum.IntEnum: | | __repr__(self) from enum.Enum | Return repr(self). | | __str__ = __repr__(self, /) from builtins.int | Return repr(self). | | ---------------------------------------------------------------------- | Methods inherited from builtins.int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __round__(...) | Rounding an Integral returns itself. | | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | __xor__(self, value, /) | Return self^value. | | as_integer_ratio(self, /) | Return a pair of integers, whose ratio is equal to the original int. | | The ratio is in lowest terms and has a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_count(self, /) | Number of ones in the binary representation of the absolute value of self. | | Also known as the population count. | | >>> bin(13) | '0b1101' | >>> (13).bit_count() | 3 | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | is_integer(self, /) | Returns True. Exists for duck type compatibility with float.is_integer. | | to_bytes(self, /, length=1, byteorder='big', *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. Default | is length 1. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from builtins.int: | | from_bytes(bytes, byteorder='big', *, signed=False) | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number | | ---------------------------------------------------------------------- | Methods inherited from enum.Enum: | | __dir__(self) | Returns public methods and other interesting attributes. | | __init__(self, *args, **kwds) | Initialize self. See help(type(self)) for accurate signature. | | __reduce_ex__(self, proto) | Helper for pickle. | | ---------------------------------------------------------------------- | Data descriptors inherited from enum.Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Static methods inherited from enum.EnumType: | | __contains__(value) | Return True if `value` is in `cls`. | | `value` is in `cls` if: | 1) `value` is a member of `cls`, or | 2) `value` is the value of one of the `cls`'s members. | | __getitem__(name) | Return the member matching `name`. | | __iter__() | Return members in definition order. | | __len__() | Return the number of members (no aliases) | | ---------------------------------------------------------------------- | Readonly properties inherited from enum.EnumType: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping.
websockets.ConcurrencyError
Python Library Documentation: class ConcurrencyError in module websockets.exceptions class ConcurrencyError(WebSocketException, builtins.RuntimeError) | Raised when receiving or sending messages concurrently. | | WebSocket is a connection-oriented protocol. Reads must be serialized; so | must be writes. However, reading and writing concurrently is possible. | | Method resolution order: | ConcurrencyError | WebSocketException | builtins.RuntimeError | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.RuntimeError: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.RuntimeError: | | __new__(*args, **kwargs) class method of builtins.RuntimeError | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.ConnectionClosed
Python Library Documentation: class ConnectionClosed in module websockets.exceptions class ConnectionClosed(WebSocketException) | ConnectionClosed(rcvd: 'frames.Close | None', sent: 'frames.Close | None', rcvd_then_sent: 'bool | None' = None) -> 'None' | | Raised when trying to interact with a closed connection. | | Attributes: | rcvd: If a close frame was received, its code and reason are available | in ``rcvd.code`` and ``rcvd.reason``. | sent: If a close frame was sent, its code and reason are available | in ``sent.code`` and ``sent.reason``. | rcvd_then_sent: If close frames were received and sent, this attribute | tells in which order this happened, from the perspective of this | side of the connection. | | Method resolution order: | ConnectionClosed | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, rcvd: 'frames.Close | None', sent: 'frames.Close | None', rcvd_then_sent: 'bool | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Readonly properties defined here: | | code | | reason | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.ConnectionClosedError
Python Library Documentation: class ConnectionClosedError in module websockets.exceptions class ConnectionClosedError(ConnectionClosed) | ConnectionClosedError(rcvd: 'frames.Close | None', sent: 'frames.Close | None', rcvd_then_sent: 'bool | None' = None) -> 'None' | | Like :exc:`ConnectionClosed`, when the connection terminated with an error. | | A close frame with a code other than 1000 (OK) or 1001 (going away) was | received or sent, or the closing handshake didn't complete properly. | | Method resolution order: | ConnectionClosedError | ConnectionClosed | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods inherited from ConnectionClosed: | | __init__(self, rcvd: 'frames.Close | None', sent: 'frames.Close | None', rcvd_then_sent: 'bool | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Readonly properties inherited from ConnectionClosed: | | code | | reason | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.ConnectionClosedOK
Python Library Documentation: class ConnectionClosedOK in module websockets.exceptions class ConnectionClosedOK(ConnectionClosed) | ConnectionClosedOK(rcvd: 'frames.Close | None', sent: 'frames.Close | None', rcvd_then_sent: 'bool | None' = None) -> 'None' | | Like :exc:`ConnectionClosed`, when the connection terminated properly. | | A close code with code 1000 (OK) or 1001 (going away) or without a code was | received and sent. | | Method resolution order: | ConnectionClosedOK | ConnectionClosed | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods inherited from ConnectionClosed: | | __init__(self, rcvd: 'frames.Close | None', sent: 'frames.Close | None', rcvd_then_sent: 'bool | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Readonly properties inherited from ConnectionClosed: | | code | | reason | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.Data
Python Library Documentation: _UnionGenericAlias in module typing
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, 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.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
websockets.DuplicateParameter
Python Library Documentation: class DuplicateParameter in module websockets.exceptions class DuplicateParameter(NegotiationError) | DuplicateParameter(name: 'str') -> 'None' | | Raised when a parameter name is repeated in an extension header. | | Method resolution order: | DuplicateParameter | NegotiationError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, name: 'str') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.ExtensionName
Python Library Documentation: NewType in module websockets.typing object
ExtensionName = class NewType(builtins.object)
| ExtensionName(name, tp)
|
| NewType creates simple unique types with almost zero runtime overhead.
|
| NewType(name, tp) is considered a subtype of tp
| by static type checkers. At runtime, NewType(name, tp) returns
| a dummy callable that simply returns its argument.
|
| Usage::
|
| UserId = NewType('UserId', int)
|
| def name_by_id(user_id: UserId) -> str:
| ...
|
| UserId('user') # Fails type check
|
| name_by_id(42) # Fails type check
| name_by_id(UserId(42)) # OK
|
| num = UserId(5) + 1 # type: int
|
| Methods defined here:
|
| __init__(self, name, tp)
| Initialize self. See help(type(self)) for accurate signature.
|
| __mro_entries__(self, bases)
|
| __or__(self, other)
| Return self|value.
|
| __reduce__(self)
| Helper for pickle.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __call__ = _idfunc(x, /)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.ExtensionParameter
Python Library Documentation: GenericAlias in module builtins class tuple(object) | tuple(iterable=(), /) | | Built-in immutable sequence. | | If no argument is given, the constructor returns an empty tuple. | If iterable is specified the tuple is initialized from iterable's items. | | If the argument is a tuple, the return value is the same object. | | Built-in subclasses: | asyncgen_hooks | UnraisableHookArgs | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return bool(key in self). | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return value*self. | | count(self, value, /) | Return number of occurrences of value. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | See PEP 585 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.
websockets.Frame
Python Library Documentation: class Frame in module websockets.frames
class Frame(builtins.object)
| Frame(opcode: 'Opcode', data: 'Union[bytes, bytearray, memoryview]', fin: 'bool' = True, rsv1: 'bool' = False, rsv2: 'bool' = False, rsv3: 'bool' = False) -> None
|
| WebSocket frame.
|
| Attributes:
| opcode: Opcode.
| data: Payload data.
| fin: FIN bit.
| rsv1: RSV1 bit.
| rsv2: RSV2 bit.
| rsv3: RSV3 bit.
|
| Only these fields are needed. The MASK bit, payload length and masking-key
| are handled on the fly when parsing and serializing frames.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, opcode: 'Opcode', data: 'Union[bytes, bytearray, memoryview]', fin: 'bool' = True, rsv1: 'bool' = False, rsv2: 'bool' = False, rsv3: 'bool' = False) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __str__(self) -> 'str'
| Return a human-readable representation of a frame.
|
| check(self) -> 'None'
| Check that reserved bits and opcode have acceptable values.
|
| Raises:
| ProtocolError: If a reserved bit or the opcode is invalid.
|
| serialize(self, *, mask: 'bool', extensions: 'Sequence[extensions.Extension] | None' = None) -> 'bytes'
| Serialize a WebSocket frame.
|
| Args:
| mask: Whether the frame should be masked i.e. whether the write
| happens on the client side.
| extensions: List of extensions, applied in order.
|
| Raises:
| ProtocolError: If the frame contains incorrect values.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| parse(read_exact: 'Callable[[int], Generator[None, None, bytes]]', *, mask: 'bool', max_size: 'int | None' = None, extensions: 'Sequence[extensions.Extension] | None' = None) -> 'Generator[None, None, Frame]'
| Parse a WebSocket frame.
|
| This is a generator-based coroutine.
|
| Args:
| read_exact: Generator-based coroutine that reads the requested
| bytes or raises an exception if there isn't enough data.
| mask: Whether the frame should be masked i.e. whether the read
| happens on the server side.
| max_size: Maximum payload size in bytes.
| extensions: List of extensions, applied in reverse order.
|
| Raises:
| EOFError: If the connection is closed without a full WebSocket frame.
| PayloadTooBig: If the frame's payload size exceeds ``max_size``.
| ProtocolError: If the frame contains incorrect values.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| MAX_LOG_SIZE = 75
|
| __annotations__ = {'data': 'Union[bytes, bytearray, memoryview]', 'fin...
|
| __dataclass_fields__ = {'data': Field(name='data',type='Union[bytes, b...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('opcode', 'data', 'fin', 'rsv1', 'rsv2', 'rsv3')
|
| fin = True
|
| rsv1 = False
|
| rsv2 = False
|
| rsv3 = False
websockets.Headers
Python Library Documentation: class Headers in module websockets.datastructures class Headers(collections.abc.MutableMapping) | Headers(*args: 'HeadersLike', **kwargs: 'str') -> 'None' | | Efficient data structure for manipulating HTTP headers. | | A :class:`list` of ``(name, values)`` is inefficient for lookups. | | A :class:`dict` doesn't suffice because header names are case-insensitive | and multiple occurrences of headers with the same name are possible. | | :class:`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, | :class:`Headers` follows this logic: | | - When getting a header with ``headers[name]``: | - if there's no value, :exc:`KeyError` is raised; | - if there's exactly one value, it's returned; | - if there's more than one value, :exc:`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, :class:`Headers` behaves like | :class:`dict`, except keys are lower-cased to provide case-insensitivity. | | Two methods support manipulating multiple values explicitly: | | - :meth:`get_all` returns a list of all values for a header; | - :meth:`raw_items` returns an iterator of ``(name, values)`` pairs. | | Method resolution order: | Headers | collections.abc.MutableMapping | collections.abc.Mapping | collections.abc.Collection | collections.abc.Sized | collections.abc.Iterable | collections.abc.Container | builtins.object | | Methods defined here: | | __contains__(self, key: 'object') -> 'bool' | | __delitem__(self, key: 'str') -> 'None' | | __eq__(self, other: 'Any') -> 'bool' | Return self==value. | | __getitem__(self, key: 'str') -> 'str' | | __init__(self, *args: 'HeadersLike', **kwargs: 'str') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self) -> 'Iterator[str]' | | __len__(self) -> 'int' | | __repr__(self) -> 'str' | Return repr(self). | | __setitem__(self, key: 'str', value: 'str') -> 'None' | | __str__(self) -> 'str' | Return str(self). | | clear(self) -> 'None' | Remove all headers. | | copy(self) -> 'Headers' | | get_all(self, key: 'str') -> 'list[str]' | Return the (possibly empty) list of all values for a header. | | Args: | key: Header name. | | raw_items(self) -> 'Iterator[tuple[str, str]]' | Return an iterator of all values as ``(name, value)`` pairs. | | serialize(self) -> 'bytes' | | update(self, *args: 'HeadersLike', **kwargs: 'str') -> 'None' | Update from a :class:`Headers` instance and/or keyword arguments. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset() | | __hash__ = None | | __orig_bases__ = (collections.abc.MutableMapping[str, str],) | | ---------------------------------------------------------------------- | Methods inherited from collections.abc.MutableMapping: | | pop(self, key, default=<object object at 0x000001F6B6D281F0>) | D.pop(k[,d]) -> v, remove specified key and return the corresponding value. | If key is not found, d is returned if given, otherwise KeyError is raised. | | popitem(self) | D.popitem() -> (k, v), remove and return some (key, value) pair | as a 2-tuple; but raise KeyError if D is empty. | | setdefault(self, key, default=None) | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D | | ---------------------------------------------------------------------- | Methods inherited from collections.abc.Mapping: | | get(self, key, default=None) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | | items(self) | D.items() -> a set-like object providing a view on D's items | | keys(self) | D.keys() -> a set-like object providing a view on D's keys | | values(self) | D.values() -> an object providing a view on D's values | | ---------------------------------------------------------------------- | Data and other attributes inherited from collections.abc.Mapping: | | __reversed__ = None | | ---------------------------------------------------------------------- | Class methods inherited from collections.abc.Collection: | | __subclasshook__(C) | Abstract classes can override this to customize issubclass(). | | This is invoked early on by abc.ABCMeta.__subclasscheck__(). | It should return True, False or NotImplemented. If it returns | NotImplemented, the normal algorithm is used. Otherwise, it | overrides the normal algorithm (and the outcome is cached). | | ---------------------------------------------------------------------- | Class methods inherited from collections.abc.Iterable: | | __class_getitem__ = GenericAlias(...) | Represent a PEP 585 generic type | | E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
websockets.HeadersLike
Python Library Documentation: _UnionGenericAlias in module typing
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, 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.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
websockets.InvalidHandshake
Python Library Documentation: class InvalidHandshake in module websockets.exceptions class InvalidHandshake(WebSocketException) | Base class for exceptions raised when the opening handshake fails. | | Method resolution order: | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidHeader
Python Library Documentation: class InvalidHeader in module websockets.exceptions class InvalidHeader(InvalidHandshake) | InvalidHeader(name: 'str', value: 'str | None' = None) -> 'None' | | Raised when an HTTP header doesn't have a valid format or value. | | Method resolution order: | InvalidHeader | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, name: 'str', value: 'str | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidHeaderFormat
Python Library Documentation: class InvalidHeaderFormat in module websockets.exceptions class InvalidHeaderFormat(InvalidHeader) | InvalidHeaderFormat(name: 'str', error: 'str', header: 'str', pos: 'int') -> 'None' | | Raised when an HTTP header cannot be parsed. | | The format of the header doesn't match the grammar for that header. | | Method resolution order: | InvalidHeaderFormat | InvalidHeader | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, name: 'str', error: 'str', header: 'str', pos: 'int') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from InvalidHeader: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidHeaderValue
Python Library Documentation: class InvalidHeaderValue in module websockets.exceptions class InvalidHeaderValue(InvalidHeader) | InvalidHeaderValue(name: 'str', value: 'str | None' = None) -> 'None' | | Raised when an HTTP header has a wrong value. | | The format of the header is correct but the value isn't acceptable. | | Method resolution order: | InvalidHeaderValue | InvalidHeader | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods inherited from InvalidHeader: | | __init__(self, name: 'str', value: 'str | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidMessage
Python Library Documentation: class InvalidMessage in module websockets.exceptions class InvalidMessage(InvalidHandshake) | Raised when a handshake request or response is malformed. | | Method resolution order: | InvalidMessage | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidOrigin
Python Library Documentation: class InvalidOrigin in module websockets.exceptions class InvalidOrigin(InvalidHeader) | InvalidOrigin(origin: 'str | None') -> 'None' | | Raised when the Origin header in a request isn't allowed. | | Method resolution order: | InvalidOrigin | InvalidHeader | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, origin: 'str | None') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from InvalidHeader: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidParameterName
Python Library Documentation: class InvalidParameterName in module websockets.exceptions class InvalidParameterName(NegotiationError) | InvalidParameterName(name: 'str') -> 'None' | | Raised when a parameter name in an extension header is invalid. | | Method resolution order: | InvalidParameterName | NegotiationError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, name: 'str') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidParameterValue
Python Library Documentation: class InvalidParameterValue in module websockets.exceptions class InvalidParameterValue(NegotiationError) | InvalidParameterValue(name: 'str', value: 'str | None') -> 'None' | | Raised when a parameter value in an extension header is invalid. | | Method resolution order: | InvalidParameterValue | NegotiationError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, name: 'str', value: 'str | None') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidProxy
Python Library Documentation: class InvalidProxy in module websockets.exceptions class InvalidProxy(WebSocketException) | InvalidProxy(proxy: 'str', msg: 'str') -> 'None' | | Raised when connecting via a proxy that isn't valid. | | Method resolution order: | InvalidProxy | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, proxy: 'str', msg: 'str') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidProxyMessage
Python Library Documentation: class InvalidProxyMessage in module websockets.exceptions class InvalidProxyMessage(ProxyError) | Raised when an HTTP proxy response is malformed. | | Method resolution order: | InvalidProxyMessage | ProxyError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidProxyStatus
Python Library Documentation: class InvalidProxyStatus in module websockets.exceptions class InvalidProxyStatus(ProxyError) | InvalidProxyStatus(response: 'http11.Response') -> 'None' | | Raised when an HTTP proxy rejects the connection. | | Method resolution order: | InvalidProxyStatus | ProxyError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, response: 'http11.Response') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidState
Python Library Documentation: class InvalidState in module websockets.exceptions class InvalidState(WebSocketException, builtins.AssertionError) | Raised when sending a frame is forbidden in the current state. | | Specifically, the Sans-I/O layer raises this exception when: | | * sending a data frame to a connection in a state other | :attr:`~websockets.protocol.State.OPEN`; | * sending a control frame to a connection in a state other than | :attr:`~websockets.protocol.State.OPEN` or | :attr:`~websockets.protocol.State.CLOSING`. | | Method resolution order: | InvalidState | WebSocketException | builtins.AssertionError | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.AssertionError: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.AssertionError: | | __new__(*args, **kwargs) class method of builtins.AssertionError | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidStatus
Python Library Documentation: class InvalidStatus in module websockets.exceptions class InvalidStatus(InvalidHandshake) | InvalidStatus(response: 'http11.Response') -> 'None' | | Raised when a handshake response rejects the WebSocket upgrade. | | Method resolution order: | InvalidStatus | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, response: 'http11.Response') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidStatusCode
Python Library Documentation: class InvalidStatusCode in module websockets.legacy.exceptions class InvalidStatusCode(websockets.exceptions.InvalidHandshake) | InvalidStatusCode(status_code: int, headers: websockets.datastructures.Headers) -> None | | Raised when a handshake response status code is invalid. | | Method resolution order: | InvalidStatusCode | websockets.exceptions.InvalidHandshake | websockets.exceptions.WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, status_code: int, headers: websockets.datastructures.Headers) -> None | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> str | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from websockets.exceptions.WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidURI
Python Library Documentation: class InvalidURI in module websockets.exceptions class InvalidURI(WebSocketException) | InvalidURI(uri: 'str', msg: 'str') -> 'None' | | Raised when connecting to a URI that isn't a valid WebSocket URI. | | Method resolution order: | InvalidURI | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, uri: 'str', msg: 'str') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.InvalidUpgrade
Python Library Documentation: class InvalidUpgrade in module websockets.exceptions class InvalidUpgrade(InvalidHeader) | InvalidUpgrade(name: 'str', value: 'str | None' = None) -> 'None' | | Raised when the Upgrade or Connection header isn't correct. | | Method resolution order: | InvalidUpgrade | InvalidHeader | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods inherited from InvalidHeader: | | __init__(self, name: 'str', value: 'str | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.LoggerLike
Python Library Documentation: _UnionGenericAlias in module typing
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, 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.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
websockets.MultipleValuesError
Python Library Documentation: class MultipleValuesError in module websockets.datastructures class MultipleValuesError(builtins.LookupError) | Exception raised when :class:`Headers` has multiple values for a key. | | Method resolution order: | MultipleValuesError | builtins.LookupError | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __str__(self) -> 'str' | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.LookupError: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.LookupError: | | __new__(*args, **kwargs) class method of builtins.LookupError | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.NegotiationError
Python Library Documentation: class NegotiationError in module websockets.exceptions class NegotiationError(InvalidHandshake) | Raised when negotiating an extension or a subprotocol fails. | | Method resolution order: | NegotiationError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.Opcode
Python Library Documentation: class Opcode in module websockets.frames class Opcode(enum.IntEnum) | Opcode(*values) | | Opcode values for WebSocket frames. | | Method resolution order: | Opcode | enum.IntEnum | builtins.int | enum.ReprEnum | enum.Enum | builtins.object | | Methods defined here: | | __format__(self, format_spec, /) from builtins.int | Convert to a string according to format_spec. | | __new__(cls, value) from enum.Enum | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | BINARY = <Opcode.BINARY: 2> | | CLOSE = <Opcode.CLOSE: 8> | | CONT = <Opcode.CONT: 0> | | PING = <Opcode.PING: 9> | | PONG = <Opcode.PONG: 10> | | TEXT = <Opcode.TEXT: 1> | | ---------------------------------------------------------------------- | Methods inherited from enum.IntEnum: | | __repr__(self) from enum.Enum | Return repr(self). | | __str__ = __repr__(self, /) from builtins.int | Return repr(self). | | ---------------------------------------------------------------------- | Methods inherited from builtins.int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __round__(...) | Rounding an Integral returns itself. | | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | __xor__(self, value, /) | Return self^value. | | as_integer_ratio(self, /) | Return a pair of integers, whose ratio is equal to the original int. | | The ratio is in lowest terms and has a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_count(self, /) | Number of ones in the binary representation of the absolute value of self. | | Also known as the population count. | | >>> bin(13) | '0b1101' | >>> (13).bit_count() | 3 | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | is_integer(self, /) | Returns True. Exists for duck type compatibility with float.is_integer. | | to_bytes(self, /, length=1, byteorder='big', *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. Default | is length 1. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from builtins.int: | | from_bytes(bytes, byteorder='big', *, signed=False) | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number | | ---------------------------------------------------------------------- | Methods inherited from enum.Enum: | | __dir__(self) | Returns public methods and other interesting attributes. | | __init__(self, *args, **kwds) | Initialize self. See help(type(self)) for accurate signature. | | __reduce_ex__(self, proto) | Helper for pickle. | | ---------------------------------------------------------------------- | Data descriptors inherited from enum.Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Static methods inherited from enum.EnumType: | | __contains__(value) | Return True if `value` is in `cls`. | | `value` is in `cls` if: | 1) `value` is a member of `cls`, or | 2) `value` is the value of one of the `cls`'s members. | | __getitem__(name) | Return the member matching `name`. | | __iter__() | Return members in definition order. | | __len__() | Return the number of members (no aliases) | | ---------------------------------------------------------------------- | Readonly properties inherited from enum.EnumType: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping.
websockets.Origin
Python Library Documentation: NewType in module websockets.typing object
Origin = class NewType(builtins.object)
| Origin(name, tp)
|
| NewType creates simple unique types with almost zero runtime overhead.
|
| NewType(name, tp) is considered a subtype of tp
| by static type checkers. At runtime, NewType(name, tp) returns
| a dummy callable that simply returns its argument.
|
| Usage::
|
| UserId = NewType('UserId', int)
|
| def name_by_id(user_id: UserId) -> str:
| ...
|
| UserId('user') # Fails type check
|
| name_by_id(42) # Fails type check
| name_by_id(UserId(42)) # OK
|
| num = UserId(5) + 1 # type: int
|
| Methods defined here:
|
| __init__(self, name, tp)
| Initialize self. See help(type(self)) for accurate signature.
|
| __mro_entries__(self, bases)
|
| __or__(self, other)
| Return self|value.
|
| __reduce__(self)
| Helper for pickle.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __call__ = _idfunc(x, /)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.PayloadTooBig
Python Library Documentation: class PayloadTooBig in module websockets.exceptions class PayloadTooBig(WebSocketException) | PayloadTooBig(size_or_message: 'int | None | str', max_size: 'int | None' = None, cur_size: 'int | None' = None) -> 'None' | | Raised when parsing a frame with a payload that exceeds the maximum size. | | The Sans-I/O layer uses this exception internally. It doesn't bubble up to | the I/O layer. | | The :meth:`~websockets.extensions.Extension.decode` method of extensions | must raise :exc:`PayloadTooBig` if decoding a frame would exceed the limit. | | Method resolution order: | PayloadTooBig | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, size_or_message: 'int | None | str', max_size: 'int | None' = None, cur_size: 'int | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> 'str' | Return str(self). | | set_current_size(self, cur_size: 'int | None') -> 'None' | | ---------------------------------------------------------------------- | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.Protocol
Python Library Documentation: class Protocol in module websockets.protocol
class Protocol(builtins.object)
| Protocol(side: 'Side', *, state: 'State' = <State.OPEN: 1>, max_size: 'int | None' = 1048576, logger: 'LoggerLike | None' = None) -> 'None'
|
| Sans-I/O implementation of a WebSocket connection.
|
| Args:
| side: :attr:`~Side.CLIENT` or :attr:`~Side.SERVER`.
| state: Initial state of the WebSocket connection.
| max_size: Maximum size of incoming messages in bytes;
| :obj:`None` disables the limit.
| logger: Logger for this connection; depending on ``side``,
| defaults to ``logging.getLogger("websockets.client")``
| or ``logging.getLogger("websockets.server")``;
| see the :doc:`logging guide <../../topics/logging>` for details.
|
| Methods defined here:
|
| __init__(self, side: 'Side', *, state: 'State' = <State.OPEN: 1>, max_size: 'int | None' = 1048576, logger: 'LoggerLike | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| close_expected(self) -> 'bool'
| Tell if the TCP connection is expected to close soon.
|
| Call this method immediately after any of the ``receive_*()``,
| ``send_close()``, or :meth:`fail` methods.
|
| If it returns :obj:`True`, schedule closing the TCP connection after a
| short timeout if the other side hasn't already closed it.
|
| Returns:
| Whether the TCP connection is expected to close soon.
|
| data_to_send(self) -> 'list[bytes]'
| Obtain data to send to the network.
|
| Call this method immediately after any of the ``receive_*()``,
| ``send_*()``, or :meth:`fail` methods.
|
| Write resulting data to the connection.
|
| The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals
| the end of the data stream. When you receive it, half-close the TCP
| connection.
|
| Returns:
| Data to write to the connection.
|
| discard(self) -> 'Generator[None]'
| Discard incoming data.
|
| This coroutine replaces :meth:`parse`:
|
| - after receiving a close frame, during a normal closure (1.4);
| - after sending a close frame, during an abnormal closure (7.1.7).
|
| events_received(self) -> 'list[Event]'
| Fetch events generated from data received from the network.
|
| Call this method immediately after any of the ``receive_*()`` methods.
|
| Process resulting events, likely by passing them to the application.
|
| Returns:
| Events read from the connection.
|
| fail(self, code: 'int', reason: 'str' = '') -> 'None'
| `Fail the WebSocket connection`_.
|
| .. _Fail the WebSocket connection:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7
|
| Parameters:
| code: close code
| reason: close reason
|
| Raises:
| ProtocolError: If the code isn't valid.
|
| parse(self) -> 'Generator[None]'
| Parse incoming data into frames.
|
| :meth:`receive_data` and :meth:`receive_eof` run this generator
| coroutine until it needs more data or reaches EOF.
|
| :meth:`parse` never raises an exception. Instead, it sets the
| :attr:`parser_exc` and yields control.
|
| receive_data(self, data: 'bytes') -> 'None'
| Receive data from the network.
|
| After calling this method:
|
| - You must call :meth:`data_to_send` and send this data to the network.
| - You should call :meth:`events_received` and process resulting events.
|
| Raises:
| EOFError: If :meth:`receive_eof` was called earlier.
|
| receive_eof(self) -> 'None'
| Receive the end of the data stream from the network.
|
| After calling this method:
|
| - You must call :meth:`data_to_send` and send this data to the network;
| it will return ``[b""]``, signaling the end of the stream, or ``[]``.
| - You aren't expected to call :meth:`events_received`; it won't return
| any new events.
|
| :meth:`receive_eof` is idempotent.
|
| recv_frame(self, frame: 'Frame') -> 'None'
| Process an incoming frame.
|
| send_binary(self, data: 'bytes', fin: 'bool' = True) -> 'None'
| Send a `Binary frame`_.
|
| .. _Binary frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing arbitrary binary data.
| fin: FIN bit; set it to :obj:`False` if this is the first frame of
| a fragmented message.
|
| Raises:
| ProtocolError: If a fragmented message is in progress.
|
| send_close(self, code: 'int | None' = None, reason: 'str' = '') -> 'None'
| Send a `Close frame`_.
|
| .. _Close frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1
|
| Parameters:
| code: close code.
| reason: close reason.
|
| Raises:
| ProtocolError: If the code isn't valid or if a reason is provided
| without a code.
|
| send_continuation(self, data: 'bytes', fin: 'bool') -> 'None'
| Send a `Continuation frame`_.
|
| .. _Continuation frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing the same kind of data
| as the initial frame.
| fin: FIN bit; set it to :obj:`True` if this is the last frame
| of a fragmented message and to :obj:`False` otherwise.
|
| Raises:
| ProtocolError: If a fragmented message isn't in progress.
|
| send_eof(self) -> 'None'
|
| send_frame(self, frame: 'Frame') -> 'None'
|
| send_ping(self, data: 'bytes') -> 'None'
| Send a `Ping frame`_.
|
| .. _Ping frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| Parameters:
| data: payload containing arbitrary binary data.
|
| send_pong(self, data: 'bytes') -> 'None'
| Send a `Pong frame`_.
|
| .. _Pong frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| Parameters:
| data: payload containing arbitrary binary data.
|
| send_text(self, data: 'bytes', fin: 'bool' = True) -> 'None'
| Send a `Text frame`_.
|
| .. _Text frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing text encoded with UTF-8.
| fin: FIN bit; set it to :obj:`False` if this is the first frame of
| a fragmented message.
|
| Raises:
| ProtocolError: If a fragmented message is in progress.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| close_code
| WebSocket close code received from the remote endpoint.
|
| Defined in 7.1.5_ of :rfc:`6455`.
|
| .. _7.1.5: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
|
| :obj:`None` if the connection isn't closed yet.
|
| close_exc
| Exception to raise when trying to interact with a closed connection.
|
| Don't raise this exception while the connection :attr:`state`
| is :attr:`~websockets.protocol.State.CLOSING`; wait until
| it's :attr:`~websockets.protocol.State.CLOSED`.
|
| Indeed, the exception includes the close code and reason, which are
| known only once the connection is closed.
|
| Raises:
| AssertionError: If the connection isn't closed yet.
|
| close_reason
| WebSocket close reason received from the remote endpoint.
|
| Defined in 7.1.6_ of :rfc:`6455`.
|
| .. _7.1.6: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
|
| :obj:`None` if the connection isn't closed yet.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| state
| State of the WebSocket connection.
|
| Defined in 4.1_, 4.2_, 7.1.3_, and 7.1.4_ of :rfc:`6455`.
|
| .. _4.1: https://datatracker.ietf.org/doc/html/rfc6455#section-4.1
| .. _4.2: https://datatracker.ietf.org/doc/html/rfc6455#section-4.2
| .. _7.1.3: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.3
| .. _7.1.4: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
websockets.ProtocolError
Python Library Documentation: class ProtocolError in module websockets.exceptions class ProtocolError(WebSocketException) | Raised when receiving or sending a frame that breaks the protocol. | | The Sans-I/O implementation raises this exception when: | | * receiving or sending a frame that contains invalid data; | * receiving or sending an invalid sequence of frames. | | Method resolution order: | ProtocolError | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.ProxyError
Python Library Documentation: class ProxyError in module websockets.exceptions class ProxyError(InvalidHandshake) | Raised when failing to connect to a proxy. | | Method resolution order: | ProxyError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.RedirectHandshake
Python Library Documentation: class RedirectHandshake in module websockets.legacy.exceptions class RedirectHandshake(websockets.exceptions.InvalidHandshake) | RedirectHandshake(uri: str) -> None | | Raised when a handshake gets redirected. | | This exception is an implementation detail. | | Method resolution order: | RedirectHandshake | websockets.exceptions.InvalidHandshake | websockets.exceptions.WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, uri: str) -> None | Initialize self. See help(type(self)) for accurate signature. | | __str__(self) -> str | Return str(self). | | ---------------------------------------------------------------------- | Data descriptors inherited from websockets.exceptions.WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.Request
Python Library Documentation: class Request in module websockets.http11
class Request(builtins.object)
| Request(path: 'str', headers: 'Headers', _exception: 'Exception | None' = None) -> None
|
| WebSocket handshake request.
|
| Attributes:
| path: Request path, including optional query.
| headers: Request headers.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, path: 'str', headers: 'Headers', _exception: 'Exception | None' = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| serialize(self) -> 'bytes'
| Serialize a WebSocket handshake request.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| parse(read_line: 'Callable[[int], Generator[None, None, bytes]]') -> 'Generator[None, None, Request]'
| Parse a WebSocket handshake request.
|
| This is a generator-based coroutine.
|
| The request path isn't URL-decoded or validated in any way.
|
| The request path and headers are expected to contain only ASCII
| characters. Other characters are represented with surrogate escapes.
|
| :meth:`parse` 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 the data stream after :meth:`parse` returns.
|
| Args:
| read_line: Generator-based coroutine that reads a LF-terminated
| line or raises an exception if there isn't enough data
|
| 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.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| exception
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_exception': 'Exception | None', 'headers': 'Heade...
|
| __dataclass_fields__ = {'_exception': Field(name='_exception',type='Ex...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('path', 'headers', '_exception')
websockets.Response
Python Library Documentation: class Response in module websockets.http11
class Response(builtins.object)
| Response(status_code: 'int', reason_phrase: 'str', headers: 'Headers', body: 'bytes' = b'', _exception: 'Exception | None' = None) -> None
|
| WebSocket handshake response.
|
| Attributes:
| status_code: Response code.
| reason_phrase: Response reason.
| headers: Response headers.
| body: Response body.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, status_code: 'int', reason_phrase: 'str', headers: 'Headers', body: 'bytes' = b'', _exception: 'Exception | None' = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| serialize(self) -> 'bytes'
| Serialize a WebSocket handshake response.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| parse(read_line: 'Callable[[int], Generator[None, None, bytes]]', read_exact: 'Callable[[int], Generator[None, None, bytes]]', read_to_eof: 'Callable[[int], Generator[None, None, bytes]]', include_body: 'bool' = True) -> 'Generator[None, None, Response]'
| Parse a WebSocket handshake response.
|
| This is a generator-based coroutine.
|
| The reason phrase and headers are expected to contain only ASCII
| characters. Other characters are represented with surrogate escapes.
|
| Args:
| read_line: Generator-based coroutine that reads a LF-terminated
| line or raises an exception if there isn't enough data.
| read_exact: Generator-based coroutine that reads the requested
| bytes or raises an exception if there isn't enough data.
| read_to_eof: Generator-based coroutine that reads until the end
| of the stream.
|
| Raises:
| EOFError: If the connection is closed without a full HTTP response.
| SecurityError: If the response exceeds a security limit.
| LookupError: If the response isn't well formatted.
| ValueError: If the response isn't well formatted.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| exception
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_exception': 'Exception | None', 'body': 'bytes', ...
|
| __dataclass_fields__ = {'_exception': Field(name='_exception',type='Ex...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('status_code', 'reason_phrase', 'headers', 'body', '...
|
| body = b''
websockets.Router
Python Library Documentation: class Router in module websockets.asyncio.router class Router(builtins.object) | Router(url_map: 'Map', server_name: 'str | None' = None, url_scheme: 'str' = 'ws') -> 'None' | | WebSocket router supporting :func:`route`. | | Methods defined here: | | __init__(self, url_map: 'Map', server_name: 'str | None' = None, url_scheme: 'str' = 'ws') -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | get_server_name(self, connection: 'ServerConnection', request: 'Request') -> 'str' | | async handler(self, connection: 'ServerConnection') -> 'None' | Handle a connection. | | not_found(self, connection: 'ServerConnection') -> 'Response' | | redirect(self, connection: 'ServerConnection', url: 'str') -> 'Response' | | route_request(self, connection: 'ServerConnection', request: 'Request') -> 'Response | None' | Route incoming request. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
websockets.SecurityError
Python Library Documentation: class SecurityError in module websockets.exceptions class SecurityError(InvalidHandshake) | Raised when a handshake request or response breaks a security rule. | | Security limits can be configured with :doc:`environment variables | <../reference/variables>`. | | Method resolution order: | SecurityError | InvalidHandshake | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.Server
Python Library Documentation: class Server in module websockets.asyncio.server
class Server(builtins.object)
| Server(handler: 'Callable[[ServerConnection], Awaitable[None]]', *, process_request: 'Callable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | None' = None, process_response: 'Callable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | None' = None, server_header: 'str | None' = 'Python/3.12 websockets/15.0.1', open_timeout: 'float | None' = 10, logger: 'LoggerLike | None' = None) -> 'None'
|
| WebSocket server returned by :func:`serve`.
|
| This class mirrors the API of :class:`asyncio.Server`.
|
| It keeps track of WebSocket connections in order to close them properly
| when shutting down.
|
| Args:
| handler: Connection handler. It receives the WebSocket connection,
| which is a :class:`ServerConnection`, in argument.
| process_request: Intercept the request during the opening handshake.
| Return an HTTP response to force the response. Return :obj:`None` to
| continue normally. When you force an HTTP 101 Continue response, the
| handshake is successful. Else, the connection is aborted.
| ``process_request`` may be a function or a coroutine.
| process_response: Intercept the response during the opening handshake.
| Modify the response or return a new HTTP response to force the
| response. Return :obj:`None` to continue normally. When you force an
| HTTP 101 Continue response, the handshake is successful. Else, the
| connection is aborted. ``process_response`` may be a function or a
| coroutine.
| server_header: Value of the ``Server`` response header.
| It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
| :obj:`None` removes the header.
| open_timeout: Timeout for opening connections in seconds.
| :obj:`None` disables the timeout.
| logger: Logger for this server.
| It defaults to ``logging.getLogger("websockets.server")``.
| See the :doc:`logging guide <../../topics/logging>` for details.
|
| Methods defined here:
|
| async __aenter__(self) -> 'Server'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
|
| __init__(self, handler: 'Callable[[ServerConnection], Awaitable[None]]', *, process_request: 'Callable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | None' = None, process_response: 'Callable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | None' = None, server_header: 'str | None' = 'Python/3.12 websockets/15.0.1', open_timeout: 'float | None' = 10, logger: 'LoggerLike | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| close(self, close_connections: 'bool' = True) -> 'None'
| Close the server.
|
| * Close the underlying :class:`asyncio.Server`.
| * When ``close_connections`` is :obj:`True`, which is the default,
| close existing connections. Specifically:
|
| * Reject opening WebSocket connections with an HTTP 503 (service
| unavailable) error. This happens when the server accepted the TCP
| connection but didn't complete the opening handshake before closing.
| * Close open WebSocket connections with close code 1001 (going away).
|
| * Wait until all connection handlers terminate.
|
| :meth:`close` is idempotent.
|
| async conn_handler(self, connection: 'ServerConnection') -> 'None'
| Handle the lifecycle of a WebSocket connection.
|
| Since this method doesn't have a caller that can handle exceptions,
| it attempts to log relevant ones.
|
| It guarantees that the TCP connection is closed before exiting.
|
| get_loop(self) -> 'asyncio.AbstractEventLoop'
| See :meth:`asyncio.Server.get_loop`.
|
| is_serving(self) -> 'bool'
| See :meth:`asyncio.Server.is_serving`.
|
| async serve_forever(self) -> 'None'
| See :meth:`asyncio.Server.serve_forever`.
|
| Typical use::
|
| server = await serve(...)
| # this coroutine doesn't return
| # canceling it stops the server
| await server.serve_forever()
|
| This is an alternative to using :func:`serve` as an asynchronous context
| manager. Shutdown is triggered by canceling :meth:`serve_forever`
| instead of exiting a :func:`serve` context.
|
| start_connection_handler(self, connection: 'ServerConnection') -> 'None'
| Register a connection with this server.
|
| async start_serving(self) -> 'None'
| See :meth:`asyncio.Server.start_serving`.
|
| Typical use::
|
| server = await serve(..., start_serving=False)
| # perform additional setup here...
| # ... then start the server
| await server.start_serving()
|
| async wait_closed(self) -> 'None'
| Wait until the server is closed.
|
| When :meth:`wait_closed` returns, all TCP connections are closed and
| all connection handlers have returned.
|
| To ensure a fast shutdown, a connection handler should always be
| awaiting at least one of:
|
| * :meth:`~ServerConnection.recv`: when the connection is closed,
| it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
| * :meth:`~ServerConnection.wait_closed`: when the connection is
| closed, it returns.
|
| Then the connection handler is immediately notified of the shutdown;
| it can clean up and exit.
|
| wrap(self, server: 'asyncio.Server') -> 'None'
| Attach to a given :class:`asyncio.Server`.
|
| Since :meth:`~asyncio.loop.create_server` doesn't support injecting a
| custom ``Server`` class, the easiest solution that doesn't rely on
| private :mod:`asyncio` APIs is to:
|
| - instantiate a :class:`Server`
| - give the protocol factory a reference to that instance
| - call :meth:`~asyncio.loop.create_server` with the factory
| - attach the resulting :class:`asyncio.Server` with this method
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| connections
| Set of active connections.
|
| This property contains all connections that completed the opening
| handshake successfully and didn't start the closing handshake yet.
| It can be useful in combination with :func:`~broadcast`.
|
| sockets
| See :attr:`asyncio.Server.sockets`.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.ServerConnection
Python Library Documentation: class ServerConnection in module websockets.asyncio.server
class ServerConnection(websockets.asyncio.connection.Connection)
| ServerConnection(protocol: 'ServerProtocol', server: 'Server', *, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768) -> 'None'
|
| :mod:`asyncio` implementation of a WebSocket server connection.
|
| :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
| receiving and sending messages.
|
| It supports asynchronous iteration to receive messages::
|
| async for message in websocket:
| await process(message)
|
| The iterator exits normally when the connection is closed with close code
| 1000 (OK) or 1001 (going away) or without a close code. It raises a
| :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
| closed with any other code.
|
| The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``,
| and ``write_limit`` arguments have the same meaning as in :func:`serve`.
|
| Args:
| protocol: Sans-I/O connection.
| server: Server that manages this connection.
|
| Method resolution order:
| ServerConnection
| websockets.asyncio.connection.Connection
| asyncio.protocols.Protocol
| asyncio.protocols.BaseProtocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, protocol: 'ServerProtocol', server: 'Server', *, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| connection_made(self, transport: 'asyncio.BaseTransport') -> 'None'
| Called when a connection is made.
|
| The argument is the transport representing the pipe connection.
| To receive data, wait for data_received() calls.
| When the connection is closed, connection_lost() is called.
|
| async handshake(self, process_request: 'Callable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | None' = None, process_response: 'Callable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | None' = None, server_header: 'str | None' = 'Python/3.12 websockets/15.0.1') -> 'None'
| Perform the opening handshake.
|
| process_event(self, event: 'Event') -> 'None'
| Process one incoming event.
|
| respond(self, status: 'StatusLike', text: 'str') -> 'Response'
| Create a plain text HTTP response.
|
| ``process_request`` and ``process_response`` may call this method to
| return an HTTP response instead of performing the WebSocket opening
| handshake.
|
| You can modify the response before returning it, for example by changing
| HTTP headers.
|
| Args:
| status: HTTP status code.
| text: HTTP response body; it will be encoded to UTF-8.
|
| Returns:
| HTTP response to send to the client.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.asyncio.connection.Connection:
|
| async __aenter__(self) -> 'Connection'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
|
| async __aiter__(self) -> 'AsyncIterator[Data]'
| Iterate on incoming messages.
|
| The iterator calls :meth:`recv` and yields messages asynchronously in an
| infinite loop.
|
| It exits when the connection is closed normally. It raises a
| :exc:`~websockets.exceptions.ConnectionClosedError` exception after a
| protocol error or a network failure.
|
| abort_pings(self) -> 'None'
| Raise ConnectionClosed in pending pings.
|
| They'll never receive a pong once the connection is closed.
|
| acknowledge_pings(self, data: 'bytes') -> 'None'
| Acknowledge pings when receiving a pong.
|
| async close(self, code: 'int' = 1000, reason: 'str' = '') -> 'None'
| Perform the closing handshake.
|
| :meth:`close` waits for the other end to complete the handshake and
| for the TCP connection to terminate.
|
| :meth:`close` is idempotent: it doesn't do anything once the
| connection is closed.
|
| Args:
| code: WebSocket close code.
| reason: WebSocket close reason.
|
| connection_lost(self, exc: 'Exception | None') -> 'None'
| Called when the connection is lost or closed.
|
| The argument is an exception object or None (the latter
| meaning a regular EOF is received or the connection was
| aborted or closed).
|
| data_received(self, data: 'bytes') -> 'None'
| Called when some data is received.
|
| The argument is a bytes object.
|
| async drain(self) -> 'None'
|
| eof_received(self) -> 'None'
| Called when the other end calls write_eof() or equivalent.
|
| If this returns a false value (including None), the transport
| will close itself. If it returns a true value, closing the
| transport is up to the protocol.
|
| async keepalive(self) -> 'None'
| Send a Ping frame and wait for a Pong frame at regular intervals.
|
| pause_writing(self) -> 'None'
| Called when the transport's buffer goes over the high-water mark.
|
| Pause and resume calls are paired -- pause_writing() is called
| once when the buffer goes strictly over the high-water mark
| (even if subsequent writes increases the buffer size even
| more), and eventually resume_writing() is called once when the
| buffer size reaches the low-water mark.
|
| Note that if the buffer size equals the high-water mark,
| pause_writing() is not called -- it must go strictly over.
| Conversely, resume_writing() is called when the buffer size is
| equal or lower than the low-water mark. These end conditions
| are important to ensure that things go as expected when either
| mark is zero.
|
| NOTE: This is the only Protocol callback that is not called
| through EventLoop.call_soon() -- if it were, it would have no
| effect when it's most needed (when the app keeps writing
| without yielding until pause_writing() is called).
|
| async ping(self, data: 'Data | None' = None) -> 'Awaitable[float]'
| Send a Ping_.
|
| .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| A ping may serve as a keepalive or as a check that the remote endpoint
| received all messages up to this point
|
| Args:
| data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
| If ``data`` is :obj:`None`, the payload is four random bytes.
|
| Returns:
| A future that will be completed when the corresponding pong is
| received. You can ignore it if you don't intend to wait. The result
| of the future is the latency of the connection in seconds.
|
| ::
|
| pong_waiter = await ws.ping()
| # only if you want to wait for the corresponding pong
| latency = await pong_waiter
|
| Raises:
| ConnectionClosed: When the connection is closed.
| ConcurrencyError: If another ping was sent with the same data and
| the corresponding pong wasn't received yet.
|
| async pong(self, data: 'Data' = b'') -> 'None'
| Send a Pong_.
|
| .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| An unsolicited pong may serve as a unidirectional heartbeat.
|
| Args:
| data: Payload of the pong. A :class:`str` will be encoded to UTF-8.
|
| Raises:
| ConnectionClosed: When the connection is closed.
|
| async recv(self, decode: 'bool | None' = None) -> 'Data'
| Receive the next message.
|
| When the connection is closed, :meth:`recv` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
| :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure
| and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure. This is how you detect the end of the
| message stream.
|
| Canceling :meth:`recv` is safe. There's no risk of losing data. The next
| invocation of :meth:`recv` will return the next message.
|
| This makes it possible to enforce a timeout by wrapping :meth:`recv` in
| :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
|
| When the message is fragmented, :meth:`recv` waits until all fragments
| are received, reassembles them, and returns the whole message.
|
| Args:
| decode: Set this flag to override the default behavior of returning
| :class:`str` or :class:`bytes`. See below for details.
|
| Returns:
| A string (:class:`str`) for a Text_ frame or a bytestring
| (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| You may override this behavior with the ``decode`` argument:
|
| * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
| return a bytestring (:class:`bytes`). This improves performance
| when decoding isn't needed, for example if the message contains
| JSON and you're using a JSON library that expects a bytestring.
| * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames
| and return a string (:class:`str`). This may be useful for
| servers that send binary frames instead of text frames.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| ConcurrencyError: If two coroutines call :meth:`recv` or
| :meth:`recv_streaming` concurrently.
|
| async recv_streaming(self, decode: 'bool | None' = None) -> 'AsyncIterator[Data]'
| Receive the next message frame by frame.
|
| This method is designed for receiving fragmented messages. It returns an
| asynchronous iterator that yields each fragment as it is received. This
| iterator must be fully consumed. Else, future calls to :meth:`recv` or
| :meth:`recv_streaming` will raise
| :exc:`~websockets.exceptions.ConcurrencyError`, making the connection
| unusable.
|
| :meth:`recv_streaming` raises the same exceptions as :meth:`recv`.
|
| Canceling :meth:`recv_streaming` before receiving the first frame is
| safe. Canceling it after receiving one or more frames leaves the
| iterator in a partially consumed state, making the connection unusable.
| Instead, you should close the connection with :meth:`close`.
|
| Args:
| decode: Set this flag to override the default behavior of returning
| :class:`str` or :class:`bytes`. See below for details.
|
| Returns:
| An iterator of strings (:class:`str`) for a Text_ frame or
| bytestrings (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| You may override this behavior with the ``decode`` argument:
|
| * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames
| and return bytestrings (:class:`bytes`). This may be useful to
| optimize performance when decoding isn't needed.
| * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames
| and return strings (:class:`str`). This is useful for servers
| that send binary frames instead of text frames.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| ConcurrencyError: If two coroutines call :meth:`recv` or
| :meth:`recv_streaming` concurrently.
|
| resume_writing(self) -> 'None'
| Called when the transport's buffer drains below the low-water mark.
|
| See pause_writing() for details.
|
| async send(self, message: 'Data | Iterable[Data] | AsyncIterable[Data]', text: 'bool | None' = None) -> 'None'
| Send a message.
|
| A string (:class:`str`) is sent as a Text_ frame. A bytestring or
| bytes-like object (:class:`bytes`, :class:`bytearray`, or
| :class:`memoryview`) is sent as a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| You may override this behavior with the ``text`` argument:
|
| * Set ``text=True`` to send a bytestring or bytes-like object
| (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a
| Text_ frame. This improves performance when the message is already
| UTF-8 encoded, for example if the message contains JSON and you're
| using a JSON library that produces a bytestring.
| * Set ``text=False`` to send a string (:class:`str`) in a Binary_
| frame. This may be useful for servers that expect binary frames
| instead of text frames.
|
| :meth:`send` also accepts an iterable or an asynchronous iterable of
| strings, bytestrings, or bytes-like objects to enable fragmentation_.
| Each item is treated as a message fragment and sent in its own frame.
| All items must be of the same type, or else :meth:`send` will raise a
| :exc:`TypeError` and the connection will be closed.
|
| .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
|
| :meth:`send` rejects dict-like objects because this is often an error.
| (If you really want to send the keys of a dict-like object as fragments,
| call its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
|
| Canceling :meth:`send` is discouraged. Instead, you should close the
| connection with :meth:`close`. Indeed, there are only two situations
| where :meth:`send` may yield control to the event loop and then get
| canceled; in both cases, :meth:`close` has the same effect and is
| more clear:
|
| 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.
| :meth:`close` will likely time out then abort the TCP connection.
| 2. ``message`` is an asynchronous iterator that yields control.
| Stopping in the middle of a fragmented message will cause a
| protocol error and the connection will be closed.
|
| When the connection is closed, :meth:`send` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
| raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure.
|
| Args:
| message: Message to send.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| TypeError: If ``message`` doesn't have a supported type.
|
| send_context(self, *, expected_state: 'State' = <State.OPEN: 1>) -> 'AsyncIterator[None]'
| Create a context for writing to the connection from user code.
|
| On entry, :meth:`send_context` checks that the connection is open; on
| exit, it writes outgoing data to the socket::
|
| async with self.send_context():
| self.protocol.send_text(message.encode())
|
| When the connection isn't open on entry, when the connection is expected
| to close on exit, or when an unexpected error happens, terminating the
| connection, :meth:`send_context` waits until the connection is closed
| then raises :exc:`~websockets.exceptions.ConnectionClosed`.
|
| send_data(self) -> 'None'
| Send outgoing data.
|
| Raises:
| OSError: When a socket operations fails.
|
| set_recv_exc(self, exc: 'BaseException | None') -> 'None'
| Set recv_exc, if not set yet.
|
| start_keepalive(self) -> 'None'
| Run :meth:`keepalive` in a task, unless keepalive is disabled.
|
| async wait_closed(self) -> 'None'
| Wait until the connection is closed.
|
| :meth:`wait_closed` waits for the closing handshake to complete and for
| the TCP connection to terminate.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from websockets.asyncio.connection.Connection:
|
| close_code
| State of the WebSocket connection, defined in :rfc:`6455`.
|
| This attribute is provided for completeness. Typical applications
| shouldn't check its value. Instead, they should inspect attributes
| of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| close_reason
| State of the WebSocket connection, defined in :rfc:`6455`.
|
| This attribute is provided for completeness. Typical applications
| shouldn't check its value. Instead, they should inspect attributes
| of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| local_address
| Local address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family.
| See :meth:`~socket.socket.getsockname`.
|
| remote_address
| Remote address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family.
| See :meth:`~socket.socket.getpeername`.
|
| state
| State of the WebSocket connection, defined in :rfc:`6455`.
|
| This attribute is provided for completeness. Typical applications
| shouldn't check its value. Instead, they should call :meth:`~recv` or
| :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed`
| exceptions.
|
| subprotocol
| Subprotocol negotiated during the opening handshake.
|
| :obj:`None` if no subprotocol was negotiated.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from websockets.asyncio.connection.Connection:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.ServerProtocol
Python Library Documentation: class ServerProtocol in module websockets.server
class ServerProtocol(websockets.protocol.Protocol)
| ServerProtocol(*, origins: 'Sequence[Origin | re.Pattern[str] | None] | None' = None, extensions: 'Sequence[ServerExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, select_subprotocol: 'Callable[[ServerProtocol, Sequence[Subprotocol]], Subprotocol | None] | None' = None, state: 'State' = <State.CONNECTING: 0>, max_size: 'int | None' = 1048576, logger: 'LoggerLike | None' = None) -> 'None'
|
| Sans-I/O implementation of a WebSocket server connection.
|
| Args:
| origins: Acceptable values of the ``Origin`` header. Values can be
| :class:`str` to test for an exact match or regular expressions
| compiled by :func:`re.compile` to test against a pattern. Include
| :obj:`None` in the list if the lack of an origin is acceptable.
| This is useful for defending against Cross-Site WebSocket
| Hijacking attacks.
| extensions: List of supported extensions, in order in which they
| should be tried.
| subprotocols: List of supported subprotocols, in order of decreasing
| preference.
| select_subprotocol: Callback for selecting a subprotocol among
| those supported by the client and the server. It has the same
| signature as the :meth:`select_subprotocol` method, including a
| :class:`ServerProtocol` instance as first argument.
| state: Initial state of the WebSocket connection.
| max_size: Maximum size of incoming messages in bytes;
| :obj:`None` disables the limit.
| logger: Logger for this connection;
| defaults to ``logging.getLogger("websockets.server")``;
| see the :doc:`logging guide <../../topics/logging>` for details.
|
| Method resolution order:
| ServerProtocol
| websockets.protocol.Protocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, origins: 'Sequence[Origin | re.Pattern[str] | None] | None' = None, extensions: 'Sequence[ServerExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, select_subprotocol: 'Callable[[ServerProtocol, Sequence[Subprotocol]], Subprotocol | None] | None' = None, state: 'State' = <State.CONNECTING: 0>, max_size: 'int | None' = 1048576, logger: 'LoggerLike | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| accept(self, request: 'Request') -> 'Response'
| Create a handshake response to accept the connection.
|
| If the handshake request is valid and the handshake successful,
| :meth:`accept` returns an HTTP response with status code 101.
|
| Else, it returns an HTTP response with another status code. This rejects
| the connection, like :meth:`reject` would.
|
| You must send the handshake response with :meth:`send_response`.
|
| You may modify the response before sending it, typically by adding HTTP
| headers.
|
| Args:
| request: WebSocket handshake request received from the client.
|
| Returns:
| WebSocket handshake response or HTTP response to send to the client.
|
| parse(self) -> 'Generator[None]'
| Parse incoming data into frames.
|
| :meth:`receive_data` and :meth:`receive_eof` run this generator
| coroutine until it needs more data or reaches EOF.
|
| :meth:`parse` never raises an exception. Instead, it sets the
| :attr:`parser_exc` and yields control.
|
| process_extensions(self, headers: 'Headers') -> 'tuple[str | None, list[Extension]]'
| Handle the Sec-WebSocket-Extensions HTTP request header.
|
| Accept or reject each extension proposed in the client request.
| Negotiate parameters for accepted extensions.
|
| Per :rfc:`6455`, negotiation rules are defined by the specification of
| each extension.
|
| To provide this level of flexibility, for each extension proposed by
| the client, we check for a match with each extension available in the
| server configuration. If no match is found, the extension is ignored.
|
| If several variants of the same extension are proposed by the client,
| it may be accepted several times, which won't make sense in general.
| Extensions must implement their own requirements. For this purpose,
| the list of previously accepted extensions is provided.
|
| This process doesn't allow the server to reorder extensions. It can
| only select a subset of the extensions proposed by the client.
|
| Other requirements, for example related to mandatory extensions or the
| order of extensions, may be implemented by overriding this method.
|
| Args:
| headers: WebSocket handshake request headers.
|
| Returns:
| ``Sec-WebSocket-Extensions`` HTTP response header and list of
| accepted extensions.
|
| Raises:
| InvalidHandshake: If the Sec-WebSocket-Extensions header is invalid.
|
| process_origin(self, headers: 'Headers') -> 'Origin | None'
| Handle the Origin HTTP request header.
|
| Args:
| headers: WebSocket handshake request headers.
|
| Returns:
| origin, if it is acceptable.
|
| Raises:
| InvalidHandshake: If the Origin header is invalid.
| InvalidOrigin: If the origin isn't acceptable.
|
| process_request(self, request: 'Request') -> 'tuple[str, str | None, str | None]'
| Check a handshake request and negotiate extensions and subprotocol.
|
| This function doesn't verify that the request is an HTTP/1.1 or higher
| GET request and doesn't check the ``Host`` header. These controls are
| usually performed earlier in the HTTP request handling code. They're
| the responsibility of the caller.
|
| Args:
| request: WebSocket handshake request received from the client.
|
| Returns:
| ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and
| ``Sec-WebSocket-Protocol`` headers for the handshake response.
|
| Raises:
| InvalidHandshake: If the handshake request is invalid;
| then the server must return 400 Bad Request error.
|
| process_subprotocol(self, headers: 'Headers') -> 'Subprotocol | None'
| Handle the Sec-WebSocket-Protocol HTTP request header.
|
| Args:
| headers: WebSocket handshake request headers.
|
| Returns:
| Subprotocol, if one was selected; this is also the value of the
| ``Sec-WebSocket-Protocol`` response header.
|
| Raises:
| InvalidHandshake: If the Sec-WebSocket-Subprotocol header is invalid.
|
| reject(self, status: 'StatusLike', text: 'str') -> 'Response'
| Create a handshake response to reject the connection.
|
| A short plain text response is the best fallback when failing to
| establish a WebSocket connection.
|
| You must send the handshake response with :meth:`send_response`.
|
| You may modify the response before sending it, for example by changing
| HTTP headers.
|
| Args:
| status: HTTP status code.
| text: HTTP response body; it will be encoded to UTF-8.
|
| Returns:
| HTTP response to send to the client.
|
| select_subprotocol(self, subprotocols: 'Sequence[Subprotocol]') -> 'Subprotocol | None'
| Pick a subprotocol among those offered by the client.
|
| If several subprotocols are supported by both the client and the server,
| pick the first one in the list declared the server.
|
| If the server doesn't support any subprotocols, continue without a
| subprotocol, regardless of what the client offers.
|
| If the server supports at least one subprotocol and the client doesn't
| offer any, abort the handshake with an HTTP 400 error.
|
| You provide a ``select_subprotocol`` argument to :class:`ServerProtocol`
| to override this logic. For example, you could accept the connection
| even if client doesn't offer a subprotocol, rather than reject it.
|
| Here's how to negotiate the ``chat`` subprotocol if the client supports
| it and continue without a subprotocol otherwise::
|
| def select_subprotocol(protocol, subprotocols):
| if "chat" in subprotocols:
| return "chat"
|
| Args:
| subprotocols: List of subprotocols offered by the client.
|
| Returns:
| Selected subprotocol, if a common subprotocol was found.
|
| :obj:`None` to continue without a subprotocol.
|
| Raises:
| NegotiationError: Custom implementations may raise this exception
| to abort the handshake with an HTTP 400 error.
|
| send_response(self, response: 'Response') -> 'None'
| Send a handshake response to the client.
|
| Args:
| response: WebSocket handshake response event to send.
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.protocol.Protocol:
|
| close_expected(self) -> 'bool'
| Tell if the TCP connection is expected to close soon.
|
| Call this method immediately after any of the ``receive_*()``,
| ``send_close()``, or :meth:`fail` methods.
|
| If it returns :obj:`True`, schedule closing the TCP connection after a
| short timeout if the other side hasn't already closed it.
|
| Returns:
| Whether the TCP connection is expected to close soon.
|
| data_to_send(self) -> 'list[bytes]'
| Obtain data to send to the network.
|
| Call this method immediately after any of the ``receive_*()``,
| ``send_*()``, or :meth:`fail` methods.
|
| Write resulting data to the connection.
|
| The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals
| the end of the data stream. When you receive it, half-close the TCP
| connection.
|
| Returns:
| Data to write to the connection.
|
| discard(self) -> 'Generator[None]'
| Discard incoming data.
|
| This coroutine replaces :meth:`parse`:
|
| - after receiving a close frame, during a normal closure (1.4);
| - after sending a close frame, during an abnormal closure (7.1.7).
|
| events_received(self) -> 'list[Event]'
| Fetch events generated from data received from the network.
|
| Call this method immediately after any of the ``receive_*()`` methods.
|
| Process resulting events, likely by passing them to the application.
|
| Returns:
| Events read from the connection.
|
| fail(self, code: 'int', reason: 'str' = '') -> 'None'
| `Fail the WebSocket connection`_.
|
| .. _Fail the WebSocket connection:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7
|
| Parameters:
| code: close code
| reason: close reason
|
| Raises:
| ProtocolError: If the code isn't valid.
|
| receive_data(self, data: 'bytes') -> 'None'
| Receive data from the network.
|
| After calling this method:
|
| - You must call :meth:`data_to_send` and send this data to the network.
| - You should call :meth:`events_received` and process resulting events.
|
| Raises:
| EOFError: If :meth:`receive_eof` was called earlier.
|
| receive_eof(self) -> 'None'
| Receive the end of the data stream from the network.
|
| After calling this method:
|
| - You must call :meth:`data_to_send` and send this data to the network;
| it will return ``[b""]``, signaling the end of the stream, or ``[]``.
| - You aren't expected to call :meth:`events_received`; it won't return
| any new events.
|
| :meth:`receive_eof` is idempotent.
|
| recv_frame(self, frame: 'Frame') -> 'None'
| Process an incoming frame.
|
| send_binary(self, data: 'bytes', fin: 'bool' = True) -> 'None'
| Send a `Binary frame`_.
|
| .. _Binary frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing arbitrary binary data.
| fin: FIN bit; set it to :obj:`False` if this is the first frame of
| a fragmented message.
|
| Raises:
| ProtocolError: If a fragmented message is in progress.
|
| send_close(self, code: 'int | None' = None, reason: 'str' = '') -> 'None'
| Send a `Close frame`_.
|
| .. _Close frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1
|
| Parameters:
| code: close code.
| reason: close reason.
|
| Raises:
| ProtocolError: If the code isn't valid or if a reason is provided
| without a code.
|
| send_continuation(self, data: 'bytes', fin: 'bool') -> 'None'
| Send a `Continuation frame`_.
|
| .. _Continuation frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing the same kind of data
| as the initial frame.
| fin: FIN bit; set it to :obj:`True` if this is the last frame
| of a fragmented message and to :obj:`False` otherwise.
|
| Raises:
| ProtocolError: If a fragmented message isn't in progress.
|
| send_eof(self) -> 'None'
|
| send_frame(self, frame: 'Frame') -> 'None'
|
| send_ping(self, data: 'bytes') -> 'None'
| Send a `Ping frame`_.
|
| .. _Ping frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| Parameters:
| data: payload containing arbitrary binary data.
|
| send_pong(self, data: 'bytes') -> 'None'
| Send a `Pong frame`_.
|
| .. _Pong frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| Parameters:
| data: payload containing arbitrary binary data.
|
| send_text(self, data: 'bytes', fin: 'bool' = True) -> 'None'
| Send a `Text frame`_.
|
| .. _Text frame:
| https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Parameters:
| data: payload containing text encoded with UTF-8.
| fin: FIN bit; set it to :obj:`False` if this is the first frame of
| a fragmented message.
|
| Raises:
| ProtocolError: If a fragmented message is in progress.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from websockets.protocol.Protocol:
|
| close_code
| WebSocket close code received from the remote endpoint.
|
| Defined in 7.1.5_ of :rfc:`6455`.
|
| .. _7.1.5: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
|
| :obj:`None` if the connection isn't closed yet.
|
| close_exc
| Exception to raise when trying to interact with a closed connection.
|
| Don't raise this exception while the connection :attr:`state`
| is :attr:`~websockets.protocol.State.CLOSING`; wait until
| it's :attr:`~websockets.protocol.State.CLOSED`.
|
| Indeed, the exception includes the close code and reason, which are
| known only once the connection is closed.
|
| Raises:
| AssertionError: If the connection isn't closed yet.
|
| close_reason
| WebSocket close reason received from the remote endpoint.
|
| Defined in 7.1.6_ of :rfc:`6455`.
|
| .. _7.1.6: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
|
| :obj:`None` if the connection isn't closed yet.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from websockets.protocol.Protocol:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| state
| State of the WebSocket connection.
|
| Defined in 4.1_, 4.2_, 7.1.3_, and 7.1.4_ of :rfc:`6455`.
|
| .. _4.1: https://datatracker.ietf.org/doc/html/rfc6455#section-4.1
| .. _4.2: https://datatracker.ietf.org/doc/html/rfc6455#section-4.2
| .. _7.1.3: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.3
| .. _7.1.4: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
websockets.Side
Python Library Documentation: class Side in module websockets.protocol class Side(enum.IntEnum) | Side(*values) | | A WebSocket connection is either a server or a client. | | Method resolution order: | Side | enum.IntEnum | builtins.int | enum.ReprEnum | enum.Enum | builtins.object | | Methods defined here: | | __format__(self, format_spec, /) from builtins.int | Convert to a string according to format_spec. | | __new__(cls, value) from enum.Enum | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | CLIENT = <Side.CLIENT: 1> | | SERVER = <Side.SERVER: 0> | | ---------------------------------------------------------------------- | Methods inherited from enum.IntEnum: | | __repr__(self) from enum.Enum | Return repr(self). | | __str__ = __repr__(self, /) from builtins.int | Return repr(self). | | ---------------------------------------------------------------------- | Methods inherited from builtins.int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __round__(...) | Rounding an Integral returns itself. | | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | __xor__(self, value, /) | Return self^value. | | as_integer_ratio(self, /) | Return a pair of integers, whose ratio is equal to the original int. | | The ratio is in lowest terms and has a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_count(self, /) | Number of ones in the binary representation of the absolute value of self. | | Also known as the population count. | | >>> bin(13) | '0b1101' | >>> (13).bit_count() | 3 | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | is_integer(self, /) | Returns True. Exists for duck type compatibility with float.is_integer. | | to_bytes(self, /, length=1, byteorder='big', *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. Default | is length 1. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from builtins.int: | | from_bytes(bytes, byteorder='big', *, signed=False) | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number | | ---------------------------------------------------------------------- | Methods inherited from enum.Enum: | | __dir__(self) | Returns public methods and other interesting attributes. | | __init__(self, *args, **kwds) | Initialize self. See help(type(self)) for accurate signature. | | __reduce_ex__(self, proto) | Helper for pickle. | | ---------------------------------------------------------------------- | Data descriptors inherited from enum.Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Static methods inherited from enum.EnumType: | | __contains__(value) | Return True if `value` is in `cls`. | | `value` is in `cls` if: | 1) `value` is a member of `cls`, or | 2) `value` is the value of one of the `cls`'s members. | | __getitem__(name) | Return the member matching `name`. | | __iter__() | Return members in definition order. | | __len__() | Return the number of members (no aliases) | | ---------------------------------------------------------------------- | Readonly properties inherited from enum.EnumType: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping.
websockets.State
Python Library Documentation: class State in module websockets.protocol class State(enum.IntEnum) | State(*values) | | A WebSocket connection is in one of these four states. | | Method resolution order: | State | enum.IntEnum | builtins.int | enum.ReprEnum | enum.Enum | builtins.object | | Methods defined here: | | __format__(self, format_spec, /) from builtins.int | Convert to a string according to format_spec. | | __new__(cls, value) from enum.Enum | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | CLOSED = <State.CLOSED: 3> | | CLOSING = <State.CLOSING: 2> | | CONNECTING = <State.CONNECTING: 0> | | OPEN = <State.OPEN: 1> | | ---------------------------------------------------------------------- | Methods inherited from enum.IntEnum: | | __repr__(self) from enum.Enum | Return repr(self). | | __str__ = __repr__(self, /) from builtins.int | Return repr(self). | | ---------------------------------------------------------------------- | Methods inherited from builtins.int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __round__(...) | Rounding an Integral returns itself. | | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | __xor__(self, value, /) | Return self^value. | | as_integer_ratio(self, /) | Return a pair of integers, whose ratio is equal to the original int. | | The ratio is in lowest terms and has a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_count(self, /) | Number of ones in the binary representation of the absolute value of self. | | Also known as the population count. | | >>> bin(13) | '0b1101' | >>> (13).bit_count() | 3 | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | is_integer(self, /) | Returns True. Exists for duck type compatibility with float.is_integer. | | to_bytes(self, /, length=1, byteorder='big', *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. Default | is length 1. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from builtins.int: | | from_bytes(bytes, byteorder='big', *, signed=False) | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number | | ---------------------------------------------------------------------- | Methods inherited from enum.Enum: | | __dir__(self) | Returns public methods and other interesting attributes. | | __init__(self, *args, **kwds) | Initialize self. See help(type(self)) for accurate signature. | | __reduce_ex__(self, proto) | Helper for pickle. | | ---------------------------------------------------------------------- | Data descriptors inherited from enum.Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Static methods inherited from enum.EnumType: | | __contains__(value) | Return True if `value` is in `cls`. | | `value` is in `cls` if: | 1) `value` is a member of `cls`, or | 2) `value` is the value of one of the `cls`'s members. | | __getitem__(name) | Return the member matching `name`. | | __iter__() | Return members in definition order. | | __len__() | Return the number of members (no aliases) | | ---------------------------------------------------------------------- | Readonly properties inherited from enum.EnumType: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping.
websockets.StatusLike
Python Library Documentation: _UnionGenericAlias in module typing
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, 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.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
websockets.Subprotocol
Python Library Documentation: NewType in module websockets.typing object
Subprotocol = class NewType(builtins.object)
| Subprotocol(name, tp)
|
| NewType creates simple unique types with almost zero runtime overhead.
|
| NewType(name, tp) is considered a subtype of tp
| by static type checkers. At runtime, NewType(name, tp) returns
| a dummy callable that simply returns its argument.
|
| Usage::
|
| UserId = NewType('UserId', int)
|
| def name_by_id(user_id: UserId) -> str:
| ...
|
| UserId('user') # Fails type check
|
| name_by_id(42) # Fails type check
| name_by_id(UserId(42)) # OK
|
| num = UserId(5) + 1 # type: int
|
| Methods defined here:
|
| __init__(self, name, tp)
| Initialize self. See help(type(self)) for accurate signature.
|
| __mro_entries__(self, bases)
|
| __or__(self, other)
| Return self|value.
|
| __reduce__(self)
| Helper for pickle.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __call__ = _idfunc(x, /)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.TYPE_CHECKING
Python Library Documentation: bool object class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object | | Methods defined here: | | __and__(self, value, /) | Return self&value. | | __invert__(self, /) | ~self | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __repr__(self, /) | Return repr(self). | | __ror__(self, value, /) | Return value|self. | | __rxor__(self, value, /) | Return value^self. | | __xor__(self, value, /) | Return self^value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __format__(self, format_spec, /) | Convert to a string according to format_spec. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __round__(...) | Rounding an Integral returns itself. | | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | as_integer_ratio(self, /) | Return a pair of integers, whose ratio is equal to the original int. | | The ratio is in lowest terms and has a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_count(self, /) | Number of ones in the binary representation of the absolute value of self. | | Also known as the population count. | | >>> bin(13) | '0b1101' | >>> (13).bit_count() | 3 | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | is_integer(self, /) | Returns True. Exists for duck type compatibility with float.is_integer. | | to_bytes(self, /, length=1, byteorder='big', *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. Default | is length 1. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from int: | | from_bytes(bytes, byteorder='big', *, signed=False) | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number
websockets.WebSocketClientProtocol
Python Library Documentation: class WebSocketClientProtocol in module websockets.legacy.client
class WebSocketClientProtocol(websockets.legacy.protocol.WebSocketCommonProtocol)
| WebSocketClientProtocol(*, logger: 'LoggerLike | None' = None, origin: 'Origin | None' = None, extensions: 'Sequence[ClientExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, extra_headers: 'HeadersLike | None' = None, user_agent_header: 'str | None' = 'Python/3.12 websockets/15.0.1', **kwargs: 'Any') -> 'None'
|
| WebSocket client connection.
|
| :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send`
| coroutines for receiving and sending messages.
|
| It supports asynchronous iteration to receive messages::
|
| async for message in websocket:
| await process(message)
|
| The iterator exits normally when the connection is closed with close code
| 1000 (OK) or 1001 (going away) or without a close code. It raises
| a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
| is closed with any other code.
|
| See :func:`connect` for the documentation of ``logger``, ``origin``,
| ``extensions``, ``subprotocols``, ``extra_headers``, and
| ``user_agent_header``.
|
| See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
| documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
| ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
|
| Method resolution order:
| WebSocketClientProtocol
| websockets.legacy.protocol.WebSocketCommonProtocol
| asyncio.protocols.Protocol
| asyncio.protocols.BaseProtocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, logger: 'LoggerLike | None' = None, origin: 'Origin | None' = None, extensions: 'Sequence[ClientExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, extra_headers: 'HeadersLike | None' = None, user_agent_header: 'str | None' = 'Python/3.12 websockets/15.0.1', **kwargs: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| async handshake(self, wsuri: 'WebSocketURI', origin: 'Origin | None' = None, available_extensions: 'Sequence[ClientExtensionFactory] | None' = None, available_subprotocols: 'Sequence[Subprotocol] | None' = None, extra_headers: 'HeadersLike | None' = None) -> 'None'
| Perform the client side of the opening handshake.
|
| Args:
| wsuri: URI of the WebSocket server.
| origin: Value of the ``Origin`` header.
| extensions: List of supported extensions, in order in which they
| should be negotiated and run.
| subprotocols: List of supported subprotocols, in order of decreasing
| preference.
| extra_headers: Arbitrary HTTP headers to add to the handshake request.
|
| Raises:
| InvalidHandshake: If the handshake fails.
|
| async read_http_response(self) -> 'tuple[int, Headers]'
| Read status line and headers from the HTTP response.
|
| If the response contains a body, it may be read from ``self.reader``
| after this coroutine returns.
|
| Raises:
| InvalidMessage: If the HTTP message is malformed or isn't an
| HTTP/1.1 GET response.
|
| write_http_request(self, path: 'str', headers: 'Headers') -> 'None'
| Write request line and headers to the HTTP request.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| process_extensions(headers: 'Headers', available_extensions: 'Sequence[ClientExtensionFactory] | None') -> 'list[Extension]'
| Handle the Sec-WebSocket-Extensions HTTP response header.
|
| Check that each extension is supported, as well as its parameters.
|
| Return the list of accepted extensions.
|
| Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the
| connection.
|
| :rfc:`6455` leaves the rules up to the specification of each
| :extension.
|
| To provide this level of flexibility, for each extension accepted by
| the server, we check for a match with each extension available in the
| client configuration. If no match is found, an exception is raised.
|
| If several variants of the same extension are accepted by the server,
| it may be configured several times, which won't make sense in general.
| Extensions must implement their own requirements. For this purpose,
| the list of previously accepted extensions is provided.
|
| Other requirements, for example related to mandatory extensions or the
| order of extensions, may be implemented by overriding this method.
|
| process_subprotocol(headers: 'Headers', available_subprotocols: 'Sequence[Subprotocol] | None') -> 'Subprotocol | None'
| Handle the Sec-WebSocket-Protocol HTTP response header.
|
| Check that it contains exactly one supported subprotocol.
|
| Return the selected subprotocol.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| is_client = True
|
| side = 'client'
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| async __aiter__(self) -> 'AsyncIterator[Data]'
| Iterate on incoming messages.
|
| The iterator exits normally when the connection is closed with the close
| code 1000 (OK) or 1001 (going away) or without a close code.
|
| It raises a :exc:`~websockets.exceptions.ConnectionClosedError`
| exception when the connection is closed with any other code.
|
| abort_pings(self) -> 'None'
| Raise ConnectionClosed in pending keepalive pings.
|
| They'll never receive a pong once the connection is closed.
|
| async close(self, code: 'int' = <CloseCode.NORMAL_CLOSURE: 1000>, reason: 'str' = '') -> 'None'
| Perform the closing handshake.
|
| :meth:`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 :meth:`wait_closed` after :meth:`close`.
|
| :meth:`close` is idempotent: it doesn't do anything once the
| connection is closed.
|
| Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given
| that errors during connection termination aren't particularly useful.
|
| Canceling :meth:`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 take care of closing the TCP
| connection.
|
| Args:
| code: WebSocket close code.
| reason: WebSocket close reason.
|
| async close_connection(self) -> 'None'
| 7.1.1. Close the WebSocket Connection
|
| When the opening handshake succeeds, :meth:`connection_open` starts
| this coroutine in a task. It waits for the data transfer phase to
| complete then it closes the TCP connection cleanly.
|
| When the opening handshake fails, :meth:`fail_connection` does the
| same. There's no data transfer phase in that case.
|
| async close_transport(self) -> 'None'
| Close the TCP connection.
|
| connection_closed_exc(self) -> 'ConnectionClosed'
|
| connection_lost(self, exc: 'Exception | None') -> 'None'
| 7.1.4. The WebSocket Connection is Closed.
|
| connection_made(self, transport: 'asyncio.BaseTransport') -> 'None'
| Configure write buffer limits.
|
| The high-water limit is defined by ``self.write_limit``.
|
| The low-water limit currently defaults to ``self.write_limit // 4`` in
| :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should
| be all right for reasonable use cases of this library.
|
| This is the earliest point where we can get hold of the transport,
| which means it's the best point for configuring it.
|
| connection_open(self) -> 'None'
| Callback when the WebSocket opening handshake completes.
|
| Enter the OPEN state and start the data transfer phase.
|
| data_received(self, data: 'bytes') -> 'None'
| Called when some data is received.
|
| The argument is a bytes object.
|
| async drain(self) -> 'None'
|
| async ensure_open(self) -> 'None'
| Check that the WebSocket connection is open.
|
| Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.
|
| eof_received(self) -> 'None'
| Close the transport after receiving EOF.
|
| The WebSocket protocol has its own closing handshake: endpoints close
| the TCP or TLS connection after sending and receiving a close frame.
|
| As a consequence, they never need to write after receiving EOF, so
| there's no reason to keep the transport open by returning :obj:`True`.
|
| Besides, that doesn't work on TLS connections.
|
| fail_connection(self, code: 'int' = <CloseCode.ABNORMAL_CLOSURE: 1006>, reason: 'str' = '') -> 'None'
| 7.1.7. Fail the WebSocket Connection
|
| This requires:
|
| 1. Stopping all processing of incoming data, which means cancelling
| :attr:`transfer_data_task`. The close code will be 1006 unless a
| close frame was received earlier.
|
| 2. Sending a close frame with an appropriate code if the opening
| handshake succeeded and the other side is likely to process it.
|
| 3. Closing the connection. :meth:`close_connection` takes care of
| this once :attr:`transfer_data_task` exits after being canceled.
|
| (The specification describes these steps in the opposite order.)
|
| async keepalive_ping(self) -> 'None'
| Send a Ping frame and wait for a Pong frame at regular intervals.
|
| This coroutine exits when the connection terminates and one of the
| following happens:
|
| - :meth:`ping` raises :exc:`ConnectionClosed`, or
| - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.
|
| pause_writing(self) -> 'None'
| Called when the transport's buffer goes over the high-water mark.
|
| Pause and resume calls are paired -- pause_writing() is called
| once when the buffer goes strictly over the high-water mark
| (even if subsequent writes increases the buffer size even
| more), and eventually resume_writing() is called once when the
| buffer size reaches the low-water mark.
|
| Note that if the buffer size equals the high-water mark,
| pause_writing() is not called -- it must go strictly over.
| Conversely, resume_writing() is called when the buffer size is
| equal or lower than the low-water mark. These end conditions
| are important to ensure that things go as expected when either
| mark is zero.
|
| NOTE: This is the only Protocol callback that is not called
| through EventLoop.call_soon() -- if it were, it would have no
| effect when it's most needed (when the app keeps writing
| without yielding until pause_writing() is called).
|
| async ping(self, data: 'Data | None' = None) -> 'Awaitable[float]'
| Send a Ping_.
|
| .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| A ping may serve as a keepalive, as a check that the remote endpoint
| received all messages up to this point, or to measure :attr:`latency`.
|
| Canceling :meth:`ping` is discouraged. If :meth:`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 :class:`~asyncio.Future` returned by :meth:`ping` has no
| effect.
|
| Args:
| data: Payload of the ping. A string will be encoded to UTF-8.
| If ``data`` is :obj:`None`, the payload is four random bytes.
|
| Returns:
| A future that will be completed when the corresponding pong is
| received. You can ignore it if you don't intend to wait. The result
| of the future is the latency of the connection in seconds.
|
| ::
|
| pong_waiter = await ws.ping()
| # only if you want to wait for the corresponding pong
| latency = await pong_waiter
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If another ping was sent with the same data and
| the corresponding pong wasn't received yet.
|
| async pong(self, data: 'Data' = b'') -> 'None'
| Send a Pong_.
|
| .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| An unsolicited pong may serve as a unidirectional heartbeat.
|
| Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return
| immediately, it means the write buffer is full. If you don't want to
| wait, you should close the connection.
|
| Args:
| data: Payload of the pong. A string will be encoded to UTF-8.
|
| Raises:
| ConnectionClosed: When the connection is closed.
|
| async read_data_frame(self, max_size: 'int | None') -> 'Frame | None'
| Read a single data frame from the connection.
|
| Process control frames received before the next data frame.
|
| Return :obj:`None` if a close frame is encountered before any data frame.
|
| async read_frame(self, max_size: 'int | None') -> 'Frame'
| Read a single frame from the connection.
|
| async read_message(self) -> 'Data | None'
| Read a single message from the connection.
|
| Re-assemble data frames if the message is fragmented.
|
| Return :obj:`None` when the closing handshake is started.
|
| async recv(self) -> 'Data'
| Receive the next message.
|
| When the connection is closed, :meth:`recv` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
| :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure. This is how you detect the end of the
| message stream.
|
| Canceling :meth:`recv` is safe. There's no risk of losing the next
| message. The next invocation of :meth:`recv` will return it.
|
| This makes it possible to enforce a timeout by wrapping :meth:`recv` in
| :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
|
| Returns:
| A string (:class:`str`) for a Text_ frame. A bytestring
| (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If two coroutines call :meth:`recv` concurrently.
|
| resume_writing(self) -> 'None'
| Called when the transport's buffer drains below the low-water mark.
|
| See pause_writing() for details.
|
| async send(self, message: 'Data | Iterable[Data] | AsyncIterable[Data]') -> 'None'
| Send a message.
|
| A string (:class:`str`) is sent as a Text_ frame. A bytestring or
| bytes-like object (:class:`bytes`, :class:`bytearray`, or
| :class:`memoryview`) is sent as a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| :meth:`send` also accepts an iterable or an asynchronous iterable of
| strings, bytestrings, or bytes-like objects to enable fragmentation_.
| Each item is treated as a message fragment and sent in its own frame.
| All items must be of the same type, or else :meth:`send` will raise a
| :exc:`TypeError` and the connection will be closed.
|
| .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
|
| :meth:`send` rejects dict-like objects because this is often an error.
| (If you want to send the keys of a dict-like object as fragments, call
| its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
|
| Canceling :meth:`send` is discouraged. Instead, you should close the
| connection with :meth:`close`. Indeed, there are only two situations
| where :meth:`send` may yield control to the event loop and then get
| canceled; in both cases, :meth:`close` has the same effect and is
| more clear:
|
| 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.
| :meth:`close` will likely time out then abort the TCP connection.
| 2. ``message`` is an asynchronous iterator that yields control.
| Stopping in the middle of a fragmented message will cause a
| protocol error and the connection will be closed.
|
| When the connection is closed, :meth:`send` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
| raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure.
|
| Args:
| message: Message to send.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| TypeError: If ``message`` doesn't have a supported type.
|
| async transfer_data(self) -> 'None'
| Read incoming messages and put them in a queue.
|
| This coroutine runs in a task until the closing handshake is started.
|
| async wait_closed(self) -> 'None'
| Wait until the connection is closed.
|
| This coroutine is identical to the :attr:`closed` attribute, except it
| can be awaited.
|
| This can make it easier to detect connection termination, regardless
| of its cause, in tasks that interact with the WebSocket connection.
|
| async wait_for_connection_lost(self) -> 'bool'
| Wait until the TCP connection is closed or ``self.close_timeout`` elapses.
|
| Return :obj:`True` if the connection is closed and :obj:`False`
| otherwise.
|
| async write_close_frame(self, close: 'Close', data: 'bytes | None' = None) -> 'None'
| Write a close frame if and only if the connection state is OPEN.
|
| This dedicated coroutine must be used for writing close frames to
| ensure that at most one close frame is sent on a given connection.
|
| async write_frame(self, fin: 'bool', opcode: 'int', data: 'bytes', *, _state: 'int' = <State.OPEN: 1>) -> 'None'
|
| write_frame_sync(self, fin: 'bool', opcode: 'int', data: 'bytes') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| close_code
| WebSocket close code, defined in `section 7.1.5 of RFC 6455`_.
|
| .. _section 7.1.5 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
|
| :obj:`None` if the connection isn't closed yet.
|
| close_reason
| WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_.
|
| .. _section 7.1.6 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
|
| :obj:`None` if the connection isn't closed yet.
|
| closed
| :obj:`True` when the connection is closed; :obj:`False` otherwise.
|
| Be aware that both :attr:`open` and :attr:`closed` are :obj:`False`
| during the opening and closing sequences.
|
| host
|
| local_address
| Local address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getsockname`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| open
| :obj:`True` when the connection is open; :obj:`False` otherwise.
|
| This attribute may be used to detect disconnections. However, this
| approach is discouraged per the EAFP_ principle. Instead, you should
| handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp
|
| port
|
| remote_address
| Remote address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getpeername`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| secure
|
| ----------------------------------------------------------------------
| Data descriptors inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.WebSocketCommonProtocol
Python Library Documentation: class WebSocketCommonProtocol in module websockets.legacy.protocol
class WebSocketCommonProtocol(asyncio.protocols.Protocol)
| WebSocketCommonProtocol(*, logger: 'LoggerLike | None' = None, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = None, max_size: 'int | None' = 1048576, max_queue: 'int | None' = 32, read_limit: 'int' = 65536, write_limit: 'int' = 65536, host: 'str | None' = None, port: 'int | None' = None, secure: 'bool | None' = None, legacy_recv: 'bool' = False, loop: 'asyncio.AbstractEventLoop | None' = None, timeout: 'float | None' = None) -> 'None'
|
| WebSocket connection.
|
| :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket
| servers and clients. You shouldn't use it directly. Instead, use
| :class:`~websockets.legacy.client.WebSocketClientProtocol` or
| :class:`~websockets.legacy.server.WebSocketServerProtocol`.
|
| This documentation focuses on low-level details that aren't covered in the
| documentation of :class:`~websockets.legacy.client.WebSocketClientProtocol`
| and :class:`~websockets.legacy.server.WebSocketServerProtocol` for the sake
| of simplicity.
|
| 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 :obj:`None` to disable this behavior.
|
| .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| 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 :obj:`None` to disable this behavior.
|
| .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| See the discussion of :doc:`keepalive <../../topics/keepalive>` for details.
|
| The ``close_timeout`` parameter defines a maximum wait time for completing
| the closing handshake and terminating the TCP connection. For legacy
| reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds
| for clients and ``4 * close_timeout`` for servers.
|
| ``close_timeout`` is a parameter of the protocol because websockets usually
| calls :meth:`close` implicitly upon exit:
|
| * on the client side, when using :func:`~websockets.legacy.client.connect`
| as a context manager;
| * on the server side, when the connection handler terminates.
|
| To apply a timeout to any other API, wrap it in :func:`~asyncio.timeout` or
| :func:`~asyncio.wait_for`.
|
| The ``max_size`` parameter enforces the maximum size for incoming messages
| in bytes. The default value is 1 MiB. If a larger message is received,
| :meth:`recv` will raise :exc:`~websockets.exceptions.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``. Messages are added
| to an in-memory queue when they're received; then :meth:`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 :meth:`recv` is called. In this situation, various receive
| buffers (at least in :mod:`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 :class:`~asyncio.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``).
|
| See the discussion of :doc:`memory usage <../../topics/memory>` for details.
|
| Args:
| logger: Logger for this server.
| It defaults to ``logging.getLogger("websockets.protocol")``.
| See the :doc:`logging guide <../../topics/logging>` for details.
| ping_interval: Interval between keepalive pings in seconds.
| :obj:`None` disables keepalive.
| ping_timeout: Timeout for keepalive pings in seconds.
| :obj:`None` disables timeouts.
| close_timeout: Timeout for closing the connection in seconds.
| For legacy reasons, the actual timeout is 4 or 5 times larger.
| max_size: Maximum size of incoming messages in bytes.
| :obj:`None` disables the limit.
| max_queue: Maximum number of incoming messages in receive buffer.
| :obj:`None` disables the limit.
| read_limit: High-water mark of read buffer in bytes.
| write_limit: High-water mark of write buffer in bytes.
|
| Method resolution order:
| WebSocketCommonProtocol
| asyncio.protocols.Protocol
| asyncio.protocols.BaseProtocol
| builtins.object
|
| Methods defined here:
|
| async __aiter__(self) -> 'AsyncIterator[Data]'
| Iterate on incoming messages.
|
| The iterator exits normally when the connection is closed with the close
| code 1000 (OK) or 1001 (going away) or without a close code.
|
| It raises a :exc:`~websockets.exceptions.ConnectionClosedError`
| exception when the connection is closed with any other code.
|
| __init__(self, *, logger: 'LoggerLike | None' = None, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = None, max_size: 'int | None' = 1048576, max_queue: 'int | None' = 32, read_limit: 'int' = 65536, write_limit: 'int' = 65536, host: 'str | None' = None, port: 'int | None' = None, secure: 'bool | None' = None, legacy_recv: 'bool' = False, loop: 'asyncio.AbstractEventLoop | None' = None, timeout: 'float | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| abort_pings(self) -> 'None'
| Raise ConnectionClosed in pending keepalive pings.
|
| They'll never receive a pong once the connection is closed.
|
| async close(self, code: 'int' = <CloseCode.NORMAL_CLOSURE: 1000>, reason: 'str' = '') -> 'None'
| Perform the closing handshake.
|
| :meth:`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 :meth:`wait_closed` after :meth:`close`.
|
| :meth:`close` is idempotent: it doesn't do anything once the
| connection is closed.
|
| Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given
| that errors during connection termination aren't particularly useful.
|
| Canceling :meth:`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 take care of closing the TCP
| connection.
|
| Args:
| code: WebSocket close code.
| reason: WebSocket close reason.
|
| async close_connection(self) -> 'None'
| 7.1.1. Close the WebSocket Connection
|
| When the opening handshake succeeds, :meth:`connection_open` starts
| this coroutine in a task. It waits for the data transfer phase to
| complete then it closes the TCP connection cleanly.
|
| When the opening handshake fails, :meth:`fail_connection` does the
| same. There's no data transfer phase in that case.
|
| async close_transport(self) -> 'None'
| Close the TCP connection.
|
| connection_closed_exc(self) -> 'ConnectionClosed'
|
| connection_lost(self, exc: 'Exception | None') -> 'None'
| 7.1.4. The WebSocket Connection is Closed.
|
| connection_made(self, transport: 'asyncio.BaseTransport') -> 'None'
| Configure write buffer limits.
|
| The high-water limit is defined by ``self.write_limit``.
|
| The low-water limit currently defaults to ``self.write_limit // 4`` in
| :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should
| be all right for reasonable use cases of this library.
|
| This is the earliest point where we can get hold of the transport,
| which means it's the best point for configuring it.
|
| connection_open(self) -> 'None'
| Callback when the WebSocket opening handshake completes.
|
| Enter the OPEN state and start the data transfer phase.
|
| data_received(self, data: 'bytes') -> 'None'
| Called when some data is received.
|
| The argument is a bytes object.
|
| async drain(self) -> 'None'
|
| async ensure_open(self) -> 'None'
| Check that the WebSocket connection is open.
|
| Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.
|
| eof_received(self) -> 'None'
| Close the transport after receiving EOF.
|
| The WebSocket protocol has its own closing handshake: endpoints close
| the TCP or TLS connection after sending and receiving a close frame.
|
| As a consequence, they never need to write after receiving EOF, so
| there's no reason to keep the transport open by returning :obj:`True`.
|
| Besides, that doesn't work on TLS connections.
|
| fail_connection(self, code: 'int' = <CloseCode.ABNORMAL_CLOSURE: 1006>, reason: 'str' = '') -> 'None'
| 7.1.7. Fail the WebSocket Connection
|
| This requires:
|
| 1. Stopping all processing of incoming data, which means cancelling
| :attr:`transfer_data_task`. The close code will be 1006 unless a
| close frame was received earlier.
|
| 2. Sending a close frame with an appropriate code if the opening
| handshake succeeded and the other side is likely to process it.
|
| 3. Closing the connection. :meth:`close_connection` takes care of
| this once :attr:`transfer_data_task` exits after being canceled.
|
| (The specification describes these steps in the opposite order.)
|
| async keepalive_ping(self) -> 'None'
| Send a Ping frame and wait for a Pong frame at regular intervals.
|
| This coroutine exits when the connection terminates and one of the
| following happens:
|
| - :meth:`ping` raises :exc:`ConnectionClosed`, or
| - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.
|
| pause_writing(self) -> 'None'
| Called when the transport's buffer goes over the high-water mark.
|
| Pause and resume calls are paired -- pause_writing() is called
| once when the buffer goes strictly over the high-water mark
| (even if subsequent writes increases the buffer size even
| more), and eventually resume_writing() is called once when the
| buffer size reaches the low-water mark.
|
| Note that if the buffer size equals the high-water mark,
| pause_writing() is not called -- it must go strictly over.
| Conversely, resume_writing() is called when the buffer size is
| equal or lower than the low-water mark. These end conditions
| are important to ensure that things go as expected when either
| mark is zero.
|
| NOTE: This is the only Protocol callback that is not called
| through EventLoop.call_soon() -- if it were, it would have no
| effect when it's most needed (when the app keeps writing
| without yielding until pause_writing() is called).
|
| async ping(self, data: 'Data | None' = None) -> 'Awaitable[float]'
| Send a Ping_.
|
| .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| A ping may serve as a keepalive, as a check that the remote endpoint
| received all messages up to this point, or to measure :attr:`latency`.
|
| Canceling :meth:`ping` is discouraged. If :meth:`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 :class:`~asyncio.Future` returned by :meth:`ping` has no
| effect.
|
| Args:
| data: Payload of the ping. A string will be encoded to UTF-8.
| If ``data`` is :obj:`None`, the payload is four random bytes.
|
| Returns:
| A future that will be completed when the corresponding pong is
| received. You can ignore it if you don't intend to wait. The result
| of the future is the latency of the connection in seconds.
|
| ::
|
| pong_waiter = await ws.ping()
| # only if you want to wait for the corresponding pong
| latency = await pong_waiter
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If another ping was sent with the same data and
| the corresponding pong wasn't received yet.
|
| async pong(self, data: 'Data' = b'') -> 'None'
| Send a Pong_.
|
| .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| An unsolicited pong may serve as a unidirectional heartbeat.
|
| Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return
| immediately, it means the write buffer is full. If you don't want to
| wait, you should close the connection.
|
| Args:
| data: Payload of the pong. A string will be encoded to UTF-8.
|
| Raises:
| ConnectionClosed: When the connection is closed.
|
| async read_data_frame(self, max_size: 'int | None') -> 'Frame | None'
| Read a single data frame from the connection.
|
| Process control frames received before the next data frame.
|
| Return :obj:`None` if a close frame is encountered before any data frame.
|
| async read_frame(self, max_size: 'int | None') -> 'Frame'
| Read a single frame from the connection.
|
| async read_message(self) -> 'Data | None'
| Read a single message from the connection.
|
| Re-assemble data frames if the message is fragmented.
|
| Return :obj:`None` when the closing handshake is started.
|
| async recv(self) -> 'Data'
| Receive the next message.
|
| When the connection is closed, :meth:`recv` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
| :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure. This is how you detect the end of the
| message stream.
|
| Canceling :meth:`recv` is safe. There's no risk of losing the next
| message. The next invocation of :meth:`recv` will return it.
|
| This makes it possible to enforce a timeout by wrapping :meth:`recv` in
| :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
|
| Returns:
| A string (:class:`str`) for a Text_ frame. A bytestring
| (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If two coroutines call :meth:`recv` concurrently.
|
| resume_writing(self) -> 'None'
| Called when the transport's buffer drains below the low-water mark.
|
| See pause_writing() for details.
|
| async send(self, message: 'Data | Iterable[Data] | AsyncIterable[Data]') -> 'None'
| Send a message.
|
| A string (:class:`str`) is sent as a Text_ frame. A bytestring or
| bytes-like object (:class:`bytes`, :class:`bytearray`, or
| :class:`memoryview`) is sent as a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| :meth:`send` also accepts an iterable or an asynchronous iterable of
| strings, bytestrings, or bytes-like objects to enable fragmentation_.
| Each item is treated as a message fragment and sent in its own frame.
| All items must be of the same type, or else :meth:`send` will raise a
| :exc:`TypeError` and the connection will be closed.
|
| .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
|
| :meth:`send` rejects dict-like objects because this is often an error.
| (If you want to send the keys of a dict-like object as fragments, call
| its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
|
| Canceling :meth:`send` is discouraged. Instead, you should close the
| connection with :meth:`close`. Indeed, there are only two situations
| where :meth:`send` may yield control to the event loop and then get
| canceled; in both cases, :meth:`close` has the same effect and is
| more clear:
|
| 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.
| :meth:`close` will likely time out then abort the TCP connection.
| 2. ``message`` is an asynchronous iterator that yields control.
| Stopping in the middle of a fragmented message will cause a
| protocol error and the connection will be closed.
|
| When the connection is closed, :meth:`send` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
| raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure.
|
| Args:
| message: Message to send.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| TypeError: If ``message`` doesn't have a supported type.
|
| async transfer_data(self) -> 'None'
| Read incoming messages and put them in a queue.
|
| This coroutine runs in a task until the closing handshake is started.
|
| async wait_closed(self) -> 'None'
| Wait until the connection is closed.
|
| This coroutine is identical to the :attr:`closed` attribute, except it
| can be awaited.
|
| This can make it easier to detect connection termination, regardless
| of its cause, in tasks that interact with the WebSocket connection.
|
| async wait_for_connection_lost(self) -> 'bool'
| Wait until the TCP connection is closed or ``self.close_timeout`` elapses.
|
| Return :obj:`True` if the connection is closed and :obj:`False`
| otherwise.
|
| async write_close_frame(self, close: 'Close', data: 'bytes | None' = None) -> 'None'
| Write a close frame if and only if the connection state is OPEN.
|
| This dedicated coroutine must be used for writing close frames to
| ensure that at most one close frame is sent on a given connection.
|
| async write_frame(self, fin: 'bool', opcode: 'int', data: 'bytes', *, _state: 'int' = <State.OPEN: 1>) -> 'None'
|
| write_frame_sync(self, fin: 'bool', opcode: 'int', data: 'bytes') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| close_code
| WebSocket close code, defined in `section 7.1.5 of RFC 6455`_.
|
| .. _section 7.1.5 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
|
| :obj:`None` if the connection isn't closed yet.
|
| close_reason
| WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_.
|
| .. _section 7.1.6 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
|
| :obj:`None` if the connection isn't closed yet.
|
| closed
| :obj:`True` when the connection is closed; :obj:`False` otherwise.
|
| Be aware that both :attr:`open` and :attr:`closed` are :obj:`False`
| during the opening and closing sequences.
|
| host
|
| local_address
| Local address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getsockname`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| open
| :obj:`True` when the connection is open; :obj:`False` otherwise.
|
| This attribute may be used to detect disconnections. However, this
| approach is discouraged per the EAFP_ principle. Instead, you should
| handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp
|
| port
|
| remote_address
| Remote address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getpeername`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| secure
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'is_client': 'bool', 'side': 'str'}
|
| side = 'undefined'
websockets.WebSocketException
Python Library Documentation: class WebSocketException in module websockets.exceptions class WebSocketException(builtins.Exception) | Base class for all exceptions defined by websockets. | | Method resolution order: | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.WebSocketProtocolError
Python Library Documentation: class ProtocolError in module websockets.exceptions class ProtocolError(WebSocketException) | Raised when receiving or sending a frame that breaks the protocol. | | The Sans-I/O implementation raises this exception when: | | * receiving or sending a frame that contains invalid data; | * receiving or sending an invalid sequence of frames. | | Method resolution order: | ProtocolError | WebSocketException | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors inherited from WebSocketException: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
websockets.WebSocketServer
Python Library Documentation: class WebSocketServer in module websockets.legacy.server
class WebSocketServer(builtins.object)
| WebSocketServer(logger: 'LoggerLike | None' = None) -> 'None'
|
| WebSocket server returned by :func:`serve`.
|
| This class mirrors the API of :class:`~asyncio.Server`.
|
| It keeps track of WebSocket connections in order to close them properly
| when shutting down.
|
| Args:
| logger: Logger for this server.
| It defaults to ``logging.getLogger("websockets.server")``.
| See the :doc:`logging guide <../../topics/logging>` for details.
|
| Methods defined here:
|
| async __aenter__(self) -> 'WebSocketServer'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
|
| __init__(self, logger: 'LoggerLike | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| close(self, close_connections: 'bool' = True) -> 'None'
| Close the server.
|
| * Close the underlying :class:`~asyncio.Server`.
| * When ``close_connections`` is :obj:`True`, which is the default,
| close existing connections. Specifically:
|
| * Reject opening WebSocket connections with an HTTP 503 (service
| unavailable) error. This happens when the server accepted the TCP
| connection but didn't complete the opening handshake before closing.
| * Close open WebSocket connections with close code 1001 (going away).
|
| * Wait until all connection handlers terminate.
|
| :meth:`close` is idempotent.
|
| get_loop(self) -> 'asyncio.AbstractEventLoop'
| See :meth:`asyncio.Server.get_loop`.
|
| is_serving(self) -> 'bool'
| See :meth:`asyncio.Server.is_serving`.
|
| register(self, protocol: 'WebSocketServerProtocol') -> 'None'
| Register a connection with this server.
|
| async serve_forever(self) -> 'None'
| See :meth:`asyncio.Server.serve_forever`.
|
| Typical use::
|
| server = await serve(...)
| # this coroutine doesn't return
| # canceling it stops the server
| await server.serve_forever()
|
| This is an alternative to using :func:`serve` as an asynchronous context
| manager. Shutdown is triggered by canceling :meth:`serve_forever`
| instead of exiting a :func:`serve` context.
|
| async start_serving(self) -> 'None'
| See :meth:`asyncio.Server.start_serving`.
|
| Typical use::
|
| server = await serve(..., start_serving=False)
| # perform additional setup here...
| # ... then start the server
| await server.start_serving()
|
| unregister(self, protocol: 'WebSocketServerProtocol') -> 'None'
| Unregister a connection with this server.
|
| async wait_closed(self) -> 'None'
| Wait until the server is closed.
|
| When :meth:`wait_closed` returns, all TCP connections are closed and
| all connection handlers have returned.
|
| To ensure a fast shutdown, a connection handler should always be
| awaiting at least one of:
|
| * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed,
| it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
| * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is
| closed, it returns.
|
| Then the connection handler is immediately notified of the shutdown;
| it can clean up and exit.
|
| wrap(self, server: 'asyncio.base_events.Server') -> 'None'
| Attach to a given :class:`~asyncio.Server`.
|
| Since :meth:`~asyncio.loop.create_server` doesn't support injecting a
| custom ``Server`` class, the easiest solution that doesn't rely on
| private :mod:`asyncio` APIs is to:
|
| - instantiate a :class:`WebSocketServer`
| - give the protocol factory a reference to that instance
| - call :meth:`~asyncio.loop.create_server` with the factory
| - attach the resulting :class:`~asyncio.Server` with this method
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| sockets
| See :attr:`asyncio.Server.sockets`.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.WebSocketServerProtocol
Python Library Documentation: class WebSocketServerProtocol in module websockets.legacy.server
class WebSocketServerProtocol(websockets.legacy.protocol.WebSocketCommonProtocol)
| WebSocketServerProtocol(ws_handler: 'Callable[[WebSocketServerProtocol], Awaitable[Any]] | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]', ws_server: 'WebSocketServer', *, logger: 'LoggerLike | None' = None, origins: 'Sequence[Origin | None] | None' = None, extensions: 'Sequence[ServerExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, extra_headers: 'HeadersLikeOrCallable | None' = None, server_header: 'str | None' = 'Python/3.12 websockets/15.0.1', process_request: 'Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None' = None, select_subprotocol: 'Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None' = None, open_timeout: 'float | None' = 10, **kwargs: 'Any') -> 'None'
|
| WebSocket server connection.
|
| :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send`
| coroutines for receiving and sending messages.
|
| It supports asynchronous iteration to receive messages::
|
| async for message in websocket:
| await process(message)
|
| The iterator exits normally when the connection is closed with close code
| 1000 (OK) or 1001 (going away) or without a close code. It raises
| a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
| is closed with any other code.
|
| You may customize the opening handshake in a subclass by
| overriding :meth:`process_request` or :meth:`select_subprotocol`.
|
| Args:
| ws_server: WebSocket server that created this connection.
|
| See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``,
| ``extensions``, ``subprotocols``, ``extra_headers``, and ``server_header``.
|
| See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
| documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
| ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
|
| Method resolution order:
| WebSocketServerProtocol
| websockets.legacy.protocol.WebSocketCommonProtocol
| asyncio.protocols.Protocol
| asyncio.protocols.BaseProtocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, ws_handler: 'Callable[[WebSocketServerProtocol], Awaitable[Any]] | Callable[[WebSocketServerProtocol, str], Awaitable[Any]]', ws_server: 'WebSocketServer', *, logger: 'LoggerLike | None' = None, origins: 'Sequence[Origin | None] | None' = None, extensions: 'Sequence[ServerExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, extra_headers: 'HeadersLikeOrCallable | None' = None, server_header: 'str | None' = 'Python/3.12 websockets/15.0.1', process_request: 'Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None' = None, select_subprotocol: 'Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None' = None, open_timeout: 'float | None' = 10, **kwargs: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| connection_made(self, transport: 'asyncio.BaseTransport') -> 'None'
| Register connection and initialize a task to handle it.
|
| async handler(self) -> 'None'
| Handle the lifecycle of a WebSocket connection.
|
| Since this method doesn't have a caller able to handle exceptions, it
| attempts to log relevant ones and guarantees that the TCP connection is
| closed before exiting.
|
| async handshake(self, origins: 'Sequence[Origin | None] | None' = None, available_extensions: 'Sequence[ServerExtensionFactory] | None' = None, available_subprotocols: 'Sequence[Subprotocol] | None' = None, extra_headers: 'HeadersLikeOrCallable | None' = None) -> 'str'
| Perform the server side of the opening handshake.
|
| Args:
| origins: List of acceptable values of the Origin HTTP header;
| include :obj:`None` if the lack of an origin is acceptable.
| extensions: List of supported extensions, in order in which they
| should be tried.
| subprotocols: List of supported subprotocols, in order of
| decreasing preference.
| extra_headers: Arbitrary HTTP headers to add to the response when
| the handshake succeeds.
|
| Returns:
| path of the URI of the request.
|
| Raises:
| InvalidHandshake: If the handshake fails.
|
| async process_request(self, path: 'str', request_headers: 'Headers') -> 'HTTPResponse | None'
| Intercept the HTTP request and return an HTTP response if appropriate.
|
| You may override this method in a :class:`WebSocketServerProtocol`
| subclass, for example:
|
| * to return an 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 an HTTP 401 Unauthorized or an
| HTTP 403 Forbidden when authentication fails.
|
| You may also override this method with the ``process_request``
| argument of :func:`serve` and :class:`WebSocketServerProtocol`. This
| is equivalent, except ``process_request`` won't have access to the
| protocol instance, so it can't store information for later use.
|
| :meth:`process_request` is expected to complete quickly. If it may run
| for a long time, then it should await :meth:`wait_closed` and exit if
| :meth:`wait_closed` completes, or else it could prevent the server
| from shutting down.
|
| Args:
| path: Request path, including optional query string.
| request_headers: Request headers.
|
| Returns:
| tuple[StatusLike, HeadersLike, bytes] | None: :obj:`None` to
| continue the WebSocket handshake normally.
|
| An HTTP response, represented by a 3-uple of the response status,
| headers, and body, to abort the WebSocket handshake and return
| that HTTP response instead.
|
| process_subprotocol(self, headers: 'Headers', available_subprotocols: 'Sequence[Subprotocol] | None') -> 'Subprotocol | None'
| Handle the Sec-WebSocket-Protocol HTTP request header.
|
| Return Sec-WebSocket-Protocol HTTP response header, which is the same
| as the selected subprotocol.
|
| Args:
| headers: Request headers.
| available_subprotocols: Optional list of supported subprotocols.
|
| Raises:
| InvalidHandshake: To abort the handshake with an HTTP 400 error.
|
| async read_http_request(self) -> 'tuple[str, Headers]'
| Read request line and headers from the HTTP request.
|
| If the request contains a body, it may be read from ``self.reader``
| after this coroutine returns.
|
| Raises:
| InvalidMessage: If the HTTP message is malformed or isn't an
| HTTP/1.1 GET request.
|
| select_subprotocol(self, client_subprotocols: 'Sequence[Subprotocol]', server_subprotocols: 'Sequence[Subprotocol]') -> 'Subprotocol | None'
| Pick a subprotocol among those supported by the client and the server.
|
| If several subprotocols are available, select the preferred subprotocol
| by giving equal weight to the preferences of the client and the server.
|
| If no subprotocol is available, proceed without a subprotocol.
|
| You may provide a ``select_subprotocol`` argument to :func:`serve` or
| :class:`WebSocketServerProtocol` to override this logic. For example,
| you could reject the handshake if the client doesn't support a
| particular subprotocol, rather than accept the handshake without that
| subprotocol.
|
| Args:
| client_subprotocols: List of subprotocols offered by the client.
| server_subprotocols: List of subprotocols available on the server.
|
| Returns:
| Selected subprotocol, if a common subprotocol was found.
|
| :obj:`None` to continue without a subprotocol.
|
| write_http_response(self, status: 'http.HTTPStatus', headers: 'Headers', body: 'bytes | None' = None) -> 'None'
| Write status line and headers to the HTTP response.
|
| This coroutine is also able to write a response body.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| process_extensions(headers: 'Headers', available_extensions: 'Sequence[ServerExtensionFactory] | None') -> 'tuple[str | None, list[Extension]]'
| Handle the Sec-WebSocket-Extensions HTTP request header.
|
| Accept or reject each extension proposed in the client request.
| Negotiate parameters for accepted extensions.
|
| Return the Sec-WebSocket-Extensions HTTP response header and the list
| of accepted extensions.
|
| :rfc:`6455` leaves the rules up to the specification of each
| :extension.
|
| To provide this level of flexibility, for each extension proposed by
| the client, we check for a match with each extension available in the
| server configuration. If no match is found, the extension is ignored.
|
| If several variants of the same extension are proposed by the client,
| it may be accepted several times, which won't make sense in general.
| Extensions must implement their own requirements. For this purpose,
| the list of previously accepted extensions is provided.
|
| This process doesn't allow the server to reorder extensions. It can
| only select a subset of the extensions proposed by the client.
|
| Other requirements, for example related to mandatory extensions or the
| order of extensions, may be implemented by overriding this method.
|
| Args:
| headers: Request headers.
| extensions: Optional list of supported extensions.
|
| Raises:
| InvalidHandshake: To abort the handshake with an HTTP 400 error.
|
| process_origin(headers: 'Headers', origins: 'Sequence[Origin | None] | None' = None) -> 'Origin | None'
| Handle the Origin HTTP request header.
|
| Args:
| headers: Request headers.
| origins: Optional list of acceptable origins.
|
| Raises:
| InvalidOrigin: If the origin isn't acceptable.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| is_client = False
|
| side = 'server'
|
| ----------------------------------------------------------------------
| Methods inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| async __aiter__(self) -> 'AsyncIterator[Data]'
| Iterate on incoming messages.
|
| The iterator exits normally when the connection is closed with the close
| code 1000 (OK) or 1001 (going away) or without a close code.
|
| It raises a :exc:`~websockets.exceptions.ConnectionClosedError`
| exception when the connection is closed with any other code.
|
| abort_pings(self) -> 'None'
| Raise ConnectionClosed in pending keepalive pings.
|
| They'll never receive a pong once the connection is closed.
|
| async close(self, code: 'int' = <CloseCode.NORMAL_CLOSURE: 1000>, reason: 'str' = '') -> 'None'
| Perform the closing handshake.
|
| :meth:`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 :meth:`wait_closed` after :meth:`close`.
|
| :meth:`close` is idempotent: it doesn't do anything once the
| connection is closed.
|
| Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given
| that errors during connection termination aren't particularly useful.
|
| Canceling :meth:`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 take care of closing the TCP
| connection.
|
| Args:
| code: WebSocket close code.
| reason: WebSocket close reason.
|
| async close_connection(self) -> 'None'
| 7.1.1. Close the WebSocket Connection
|
| When the opening handshake succeeds, :meth:`connection_open` starts
| this coroutine in a task. It waits for the data transfer phase to
| complete then it closes the TCP connection cleanly.
|
| When the opening handshake fails, :meth:`fail_connection` does the
| same. There's no data transfer phase in that case.
|
| async close_transport(self) -> 'None'
| Close the TCP connection.
|
| connection_closed_exc(self) -> 'ConnectionClosed'
|
| connection_lost(self, exc: 'Exception | None') -> 'None'
| 7.1.4. The WebSocket Connection is Closed.
|
| connection_open(self) -> 'None'
| Callback when the WebSocket opening handshake completes.
|
| Enter the OPEN state and start the data transfer phase.
|
| data_received(self, data: 'bytes') -> 'None'
| Called when some data is received.
|
| The argument is a bytes object.
|
| async drain(self) -> 'None'
|
| async ensure_open(self) -> 'None'
| Check that the WebSocket connection is open.
|
| Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.
|
| eof_received(self) -> 'None'
| Close the transport after receiving EOF.
|
| The WebSocket protocol has its own closing handshake: endpoints close
| the TCP or TLS connection after sending and receiving a close frame.
|
| As a consequence, they never need to write after receiving EOF, so
| there's no reason to keep the transport open by returning :obj:`True`.
|
| Besides, that doesn't work on TLS connections.
|
| fail_connection(self, code: 'int' = <CloseCode.ABNORMAL_CLOSURE: 1006>, reason: 'str' = '') -> 'None'
| 7.1.7. Fail the WebSocket Connection
|
| This requires:
|
| 1. Stopping all processing of incoming data, which means cancelling
| :attr:`transfer_data_task`. The close code will be 1006 unless a
| close frame was received earlier.
|
| 2. Sending a close frame with an appropriate code if the opening
| handshake succeeded and the other side is likely to process it.
|
| 3. Closing the connection. :meth:`close_connection` takes care of
| this once :attr:`transfer_data_task` exits after being canceled.
|
| (The specification describes these steps in the opposite order.)
|
| async keepalive_ping(self) -> 'None'
| Send a Ping frame and wait for a Pong frame at regular intervals.
|
| This coroutine exits when the connection terminates and one of the
| following happens:
|
| - :meth:`ping` raises :exc:`ConnectionClosed`, or
| - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.
|
| pause_writing(self) -> 'None'
| Called when the transport's buffer goes over the high-water mark.
|
| Pause and resume calls are paired -- pause_writing() is called
| once when the buffer goes strictly over the high-water mark
| (even if subsequent writes increases the buffer size even
| more), and eventually resume_writing() is called once when the
| buffer size reaches the low-water mark.
|
| Note that if the buffer size equals the high-water mark,
| pause_writing() is not called -- it must go strictly over.
| Conversely, resume_writing() is called when the buffer size is
| equal or lower than the low-water mark. These end conditions
| are important to ensure that things go as expected when either
| mark is zero.
|
| NOTE: This is the only Protocol callback that is not called
| through EventLoop.call_soon() -- if it were, it would have no
| effect when it's most needed (when the app keeps writing
| without yielding until pause_writing() is called).
|
| async ping(self, data: 'Data | None' = None) -> 'Awaitable[float]'
| Send a Ping_.
|
| .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2
|
| A ping may serve as a keepalive, as a check that the remote endpoint
| received all messages up to this point, or to measure :attr:`latency`.
|
| Canceling :meth:`ping` is discouraged. If :meth:`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 :class:`~asyncio.Future` returned by :meth:`ping` has no
| effect.
|
| Args:
| data: Payload of the ping. A string will be encoded to UTF-8.
| If ``data`` is :obj:`None`, the payload is four random bytes.
|
| Returns:
| A future that will be completed when the corresponding pong is
| received. You can ignore it if you don't intend to wait. The result
| of the future is the latency of the connection in seconds.
|
| ::
|
| pong_waiter = await ws.ping()
| # only if you want to wait for the corresponding pong
| latency = await pong_waiter
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If another ping was sent with the same data and
| the corresponding pong wasn't received yet.
|
| async pong(self, data: 'Data' = b'') -> 'None'
| Send a Pong_.
|
| .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3
|
| An unsolicited pong may serve as a unidirectional heartbeat.
|
| Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return
| immediately, it means the write buffer is full. If you don't want to
| wait, you should close the connection.
|
| Args:
| data: Payload of the pong. A string will be encoded to UTF-8.
|
| Raises:
| ConnectionClosed: When the connection is closed.
|
| async read_data_frame(self, max_size: 'int | None') -> 'Frame | None'
| Read a single data frame from the connection.
|
| Process control frames received before the next data frame.
|
| Return :obj:`None` if a close frame is encountered before any data frame.
|
| async read_frame(self, max_size: 'int | None') -> 'Frame'
| Read a single frame from the connection.
|
| async read_message(self) -> 'Data | None'
| Read a single message from the connection.
|
| Re-assemble data frames if the message is fragmented.
|
| Return :obj:`None` when the closing handshake is started.
|
| async recv(self) -> 'Data'
| Receive the next message.
|
| When the connection is closed, :meth:`recv` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises
| :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure. This is how you detect the end of the
| message stream.
|
| Canceling :meth:`recv` is safe. There's no risk of losing the next
| message. The next invocation of :meth:`recv` will return it.
|
| This makes it possible to enforce a timeout by wrapping :meth:`recv` in
| :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`.
|
| Returns:
| A string (:class:`str`) for a Text_ frame. A bytestring
| (:class:`bytes`) for a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| Raises:
| ConnectionClosed: When the connection is closed.
| RuntimeError: If two coroutines call :meth:`recv` concurrently.
|
| resume_writing(self) -> 'None'
| Called when the transport's buffer drains below the low-water mark.
|
| See pause_writing() for details.
|
| async send(self, message: 'Data | Iterable[Data] | AsyncIterable[Data]') -> 'None'
| Send a message.
|
| A string (:class:`str`) is sent as a Text_ frame. A bytestring or
| bytes-like object (:class:`bytes`, :class:`bytearray`, or
| :class:`memoryview`) is sent as a Binary_ frame.
|
| .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
| .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
|
| :meth:`send` also accepts an iterable or an asynchronous iterable of
| strings, bytestrings, or bytes-like objects to enable fragmentation_.
| Each item is treated as a message fragment and sent in its own frame.
| All items must be of the same type, or else :meth:`send` will raise a
| :exc:`TypeError` and the connection will be closed.
|
| .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4
|
| :meth:`send` rejects dict-like objects because this is often an error.
| (If you want to send the keys of a dict-like object as fragments, call
| its :meth:`~dict.keys` method and pass the result to :meth:`send`.)
|
| Canceling :meth:`send` is discouraged. Instead, you should close the
| connection with :meth:`close`. Indeed, there are only two situations
| where :meth:`send` may yield control to the event loop and then get
| canceled; in both cases, :meth:`close` has the same effect and is
| more clear:
|
| 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.
| :meth:`close` will likely time out then abort the TCP connection.
| 2. ``message`` is an asynchronous iterator that yields control.
| Stopping in the middle of a fragmented message will cause a
| protocol error and the connection will be closed.
|
| When the connection is closed, :meth:`send` raises
| :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
| raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
| connection closure and
| :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
| error or a network failure.
|
| Args:
| message: Message to send.
|
| Raises:
| ConnectionClosed: When the connection is closed.
| TypeError: If ``message`` doesn't have a supported type.
|
| async transfer_data(self) -> 'None'
| Read incoming messages and put them in a queue.
|
| This coroutine runs in a task until the closing handshake is started.
|
| async wait_closed(self) -> 'None'
| Wait until the connection is closed.
|
| This coroutine is identical to the :attr:`closed` attribute, except it
| can be awaited.
|
| This can make it easier to detect connection termination, regardless
| of its cause, in tasks that interact with the WebSocket connection.
|
| async wait_for_connection_lost(self) -> 'bool'
| Wait until the TCP connection is closed or ``self.close_timeout`` elapses.
|
| Return :obj:`True` if the connection is closed and :obj:`False`
| otherwise.
|
| async write_close_frame(self, close: 'Close', data: 'bytes | None' = None) -> 'None'
| Write a close frame if and only if the connection state is OPEN.
|
| This dedicated coroutine must be used for writing close frames to
| ensure that at most one close frame is sent on a given connection.
|
| async write_frame(self, fin: 'bool', opcode: 'int', data: 'bytes', *, _state: 'int' = <State.OPEN: 1>) -> 'None'
|
| write_frame_sync(self, fin: 'bool', opcode: 'int', data: 'bytes') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| close_code
| WebSocket close code, defined in `section 7.1.5 of RFC 6455`_.
|
| .. _section 7.1.5 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
|
| :obj:`None` if the connection isn't closed yet.
|
| close_reason
| WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_.
|
| .. _section 7.1.6 of RFC 6455:
| https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
|
| :obj:`None` if the connection isn't closed yet.
|
| closed
| :obj:`True` when the connection is closed; :obj:`False` otherwise.
|
| Be aware that both :attr:`open` and :attr:`closed` are :obj:`False`
| during the opening and closing sequences.
|
| host
|
| local_address
| Local address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getsockname`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| open
| :obj:`True` when the connection is open; :obj:`False` otherwise.
|
| This attribute may be used to detect disconnections. However, this
| approach is discouraged per the EAFP_ principle. Instead, you should
| handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions.
|
| .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp
|
| port
|
| remote_address
| Remote address of the connection.
|
| For IPv4 connections, this is a ``(host, port)`` tuple.
|
| The format of the address depends on the address family;
| see :meth:`~socket.socket.getpeername`.
|
| :obj:`None` if the TCP connection isn't established yet.
|
| secure
|
| ----------------------------------------------------------------------
| Data descriptors inherited from websockets.legacy.protocol.WebSocketCommonProtocol:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.WebSocketURI
Python Library Documentation: class WebSocketURI in module websockets.uri
class WebSocketURI(builtins.object)
| WebSocketURI(secure: 'bool', host: 'str', port: 'int', path: 'str', query: 'str', username: 'str | None' = None, password: 'str | None' = None) -> None
|
| WebSocket URI.
|
| Attributes:
| secure: :obj:`True` for a ``wss`` URI, :obj:`False` for a ``ws`` URI.
| host: Normalized to lower case.
| port: Always set even if it's the default.
| path: May be empty.
| query: May be empty if the URI doesn't include a query component.
| username: Available when the URI contains `User Information`_.
| password: Available when the URI contains `User Information`_.
|
| .. _User Information: https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, secure: 'bool', host: 'str', port: 'int', path: 'str', query: 'str', username: 'str | None' = None, password: 'str | None' = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| resource_name
|
| user_info
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'host': 'str', 'password': 'str | None', 'path': 's...
|
| __dataclass_fields__ = {'host': Field(name='host',type='str',default=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('secure', 'host', 'port', 'path', 'query', 'username...
|
| password = None
|
| username = None
websockets.annotations
Python Library Documentation: _Feature in module __future__ object class _Feature(builtins.object) | _Feature(optionalRelease, mandatoryRelease, compiler_flag) | | Methods defined here: | | __init__(self, optionalRelease, mandatoryRelease, compiler_flag) | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) | Return repr(self). | | getMandatoryRelease(self) | Return release in which this feature will become mandatory. | | This is a 5-tuple, of the same form as sys.version_info, or, if | the feature was dropped, or the release date is undetermined, is None. | | getOptionalRelease(self) | Return first release in which this feature was recognized. | | This is a 5-tuple, of the same form as sys.version_info. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
websockets.basic_auth
Python Library Documentation: function basic_auth in module websockets.asyncio.server
basic_auth(realm: 'str' = '', credentials: 'tuple[str, str] | Iterable[tuple[str, str]] | None' = None, check_credentials: 'Callable[[str, str], Awaitable[bool] | bool] | None' = None) -> 'Callable[[ServerConnection, Request], Awaitable[Response | None]]'
Factory for ``process_request`` to enforce HTTP Basic Authentication.
:func:`basic_auth` is designed to integrate with :func:`serve` as follows::
from websockets.asyncio.server import basic_auth, serve
async with serve(
...,
process_request=basic_auth(
realm="my dev server",
credentials=("hello", "iloveyou"),
),
):
If authentication succeeds, the connection's ``username`` attribute is set.
If it fails, the server responds with an HTTP 401 Unauthorized status.
One of ``credentials`` or ``check_credentials`` must be provided; not both.
Args:
realm: 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: Hard coded authorized credentials. It can be a
``(username, password)`` pair or a list of such pairs.
check_credentials: Function or coroutine that verifies credentials.
It receives ``username`` and ``password`` arguments and returns
whether they're valid.
Raises:
TypeError: If ``credentials`` or ``check_credentials`` is wrong.
ValueError: If ``credentials`` and ``check_credentials`` are both
provided or both not provided.
websockets.basic_auth_protocol_factory
Python Library Documentation: function basic_auth_protocol_factory in module websockets.legacy.auth
basic_auth_protocol_factory(realm: 'str | None' = None, credentials: 'Credentials | Iterable[Credentials] | None' = None, check_credentials: 'Callable[[str, str], Awaitable[bool]] | None' = None, create_protocol: 'Callable[..., BasicAuthWebSocketServerProtocol] | None' = None) -> 'Callable[..., BasicAuthWebSocketServerProtocol]'
Protocol factory that enforces HTTP Basic Auth.
:func:`basic_auth_protocol_factory` is designed to integrate with
:func:`~websockets.legacy.server.serve` like this::
serve(
...,
create_protocol=basic_auth_protocol_factory(
realm="my dev server",
credentials=("hello", "iloveyou"),
)
)
Args:
realm: 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: Hard coded authorized credentials. It can be a
``(username, password)`` pair or a list of such pairs.
check_credentials: Coroutine that verifies credentials.
It receives ``username`` and ``password`` arguments
and returns a :class:`bool`. One of ``credentials`` or
``check_credentials`` must be provided but not both.
create_protocol: Factory that creates the protocol. By default, this
is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced
by a subclass.
Raises:
TypeError: If the ``credentials`` or ``check_credentials`` argument is
wrong.
websockets.broadcast
Python Library Documentation: function broadcast in module websockets.asyncio.server
broadcast(connections: 'Iterable[Connection]', message: 'Data', raise_exceptions: 'bool' = False) -> 'None'
Broadcast a message to several WebSocket connections.
A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like
object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent
as a Binary_ frame.
.. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
.. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6
:func:`broadcast` pushes the message synchronously to all connections even
if their write buffers are overflowing. There's no backpressure.
If you broadcast messages faster than a connection can handle them, messages
will pile up in its write buffer until the connection times out. Keep
``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage
from slow connections.
Unlike :meth:`~websockets.asyncio.connection.Connection.send`,
:func:`broadcast` doesn't support sending fragmented messages. Indeed,
fragmentation is useful for sending large messages without buffering them in
memory, while :func:`broadcast` buffers one copy per connection as fast as
possible.
:func:`broadcast` skips connections that aren't open in order to avoid
errors on connections where the closing handshake is in progress.
:func:`broadcast` ignores failures to write the message on some connections.
It continues writing to other connections. On Python 3.11 and above, you may
set ``raise_exceptions`` to :obj:`True` to record failures and raise all
exceptions in a :pep:`654` :exc:`ExceptionGroup`.
While :func:`broadcast` makes more sense for servers, it works identically
with clients, if you have a use case for opening connections to many servers
and broadcasting a message to them.
Args:
websockets: WebSocket connections to which the message will be sent.
message: Message to send.
raise_exceptions: Whether to raise an exception in case of failures.
Raises:
TypeError: If ``message`` doesn't have a supported type.
websockets.connect
Python Library Documentation: class connect in module websockets.asyncio.client
class connect(builtins.object)
| connect(uri: 'str', *, origin: 'Origin | None' = None, extensions: 'Sequence[ClientExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, compression: 'str | None' = 'deflate', additional_headers: 'HeadersLike | None' = None, user_agent_header: 'str | None' = 'Python/3.12 websockets/15.0.1', proxy: 'str | Literal[True] | None' = True, process_exception: 'Callable[[Exception], Exception | None]' = <function process_exception at 0x000001F6B95A1080>, open_timeout: 'float | None' = 10, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_size: 'int | None' = 1048576, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768, logger: 'LoggerLike | None' = None, create_connection: 'type[ClientConnection] | None' = None, **kwargs: 'Any') -> 'None'
|
| Connect to the WebSocket server at ``uri``.
|
| This coroutine returns a :class:`ClientConnection` instance, which you can
| use to send and receive messages.
|
| :func:`connect` may be used as an asynchronous context manager::
|
| from websockets.asyncio.client import connect
|
| async with connect(...) as websocket:
| ...
|
| The connection is closed automatically when exiting the context.
|
| :func:`connect` can be used as an infinite asynchronous iterator to
| reconnect automatically on errors::
|
| async for websocket in connect(...):
| try:
| ...
| except websockets.exceptions.ConnectionClosed:
| continue
|
| If the connection fails with a transient error, it is retried with
| exponential backoff. If it fails with a fatal error, the exception is
| raised, breaking out of the loop.
|
| The connection is closed automatically after each iteration of the loop.
|
| Args:
| uri: URI of the WebSocket server.
| origin: Value of the ``Origin`` header, for servers that require it.
| extensions: List of supported extensions, in order in which they
| should be negotiated and run.
| subprotocols: List of supported subprotocols, in order of decreasing
| preference.
| compression: The "permessage-deflate" extension is enabled by default.
| Set ``compression`` to :obj:`None` to disable it. See the
| :doc:`compression guide <../../topics/compression>` for details.
| additional_headers (HeadersLike | None): Arbitrary HTTP headers to add
| to the handshake request.
| user_agent_header: Value of the ``User-Agent`` request header.
| It defaults to ``"Python/x.y.z websockets/X.Y"``.
| Setting it to :obj:`None` removes the header.
| proxy: If a proxy is configured, it is used by default. Set ``proxy``
| to :obj:`None` to disable the proxy or to the address of a proxy
| to override the system configuration. See the :doc:`proxy docs
| <../../topics/proxies>` for details.
| process_exception: When reconnecting automatically, tell whether an
| error is transient or fatal. The default behavior is defined by
| :func:`process_exception`. Refer to its documentation for details.
| open_timeout: Timeout for opening the connection in seconds.
| :obj:`None` disables the timeout.
| ping_interval: Interval between keepalive pings in seconds.
| :obj:`None` disables keepalive.
| ping_timeout: Timeout for keepalive pings in seconds.
| :obj:`None` disables timeouts.
| close_timeout: Timeout for closing the connection in seconds.
| :obj:`None` disables the timeout.
| max_size: Maximum size of incoming messages in bytes.
| :obj:`None` disables the limit.
| max_queue: High-water mark of the buffer where frames are received.
| It defaults to 16 frames. The low-water mark defaults to ``max_queue
| // 4``. You may pass a ``(high, low)`` tuple to set the high-water
| and low-water marks. If you want to disable flow control entirely,
| you may set it to ``None``, although that's a bad idea.
| write_limit: High-water mark of write buffer in bytes. It is passed to
| :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults
| to 32 KiB. You may pass a ``(high, low)`` tuple to set the
| high-water and low-water marks.
| logger: Logger for this client.
| It defaults to ``logging.getLogger("websockets.client")``.
| See the :doc:`logging guide <../../topics/logging>` for details.
| create_connection: Factory for the :class:`ClientConnection` managing
| the connection. Set it to a wrapper or a subclass to customize
| connection handling.
|
| Any other keyword arguments are passed to the event loop's
| :meth:`~asyncio.loop.create_connection` method.
|
| For example:
|
| * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS settings.
| When connecting to a ``wss://`` URI, if ``ssl`` isn't provided, a TLS
| context is created with :func:`~ssl.create_default_context`.
|
| * You can set ``server_hostname`` to override the host name from ``uri`` in
| the TLS handshake.
|
| * You can set ``host`` and ``port`` to connect to a different host and port
| from those found in ``uri``. 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`` header.
|
| * You can set ``sock`` to provide a preexisting TCP socket. You may call
| :func:`socket.create_connection` (not to be confused with the event loop's
| :meth:`~asyncio.loop.create_connection` method) to create a suitable
| client socket and customize it.
|
| When using a proxy:
|
| * Prefix keyword arguments with ``proxy_`` for configuring TLS between the
| client and an HTTPS proxy: ``proxy_ssl``, ``proxy_server_hostname``,
| ``proxy_ssl_handshake_timeout``, and ``proxy_ssl_shutdown_timeout``.
| * Use the standard keyword arguments for configuring TLS between the proxy
| and the WebSocket server: ``ssl``, ``server_hostname``,
| ``ssl_handshake_timeout``, and ``ssl_shutdown_timeout``.
| * Other keyword arguments are used only for connecting to the proxy.
|
| Raises:
| InvalidURI: If ``uri`` isn't a valid WebSocket URI.
| InvalidProxy: If ``proxy`` isn't a valid proxy.
| OSError: If the TCP connection fails.
| InvalidHandshake: If the opening handshake fails.
| TimeoutError: If the opening handshake times out.
|
| Methods defined here:
|
| async __aenter__(self) -> 'ClientConnection'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
|
| async __aiter__(self) -> 'AsyncIterator[ClientConnection]'
|
| __await__(self) -> 'Generator[Any, None, ClientConnection]'
|
| async __await_impl__(self) -> 'ClientConnection'
|
| __init__(self, uri: 'str', *, origin: 'Origin | None' = None, extensions: 'Sequence[ClientExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, compression: 'str | None' = 'deflate', additional_headers: 'HeadersLike | None' = None, user_agent_header: 'str | None' = 'Python/3.12 websockets/15.0.1', proxy: 'str | Literal[True] | None' = True, process_exception: 'Callable[[Exception], Exception | None]' = <function process_exception at 0x000001F6B95A1080>, open_timeout: 'float | None' = 10, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_size: 'int | None' = 1048576, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768, logger: 'LoggerLike | None' = None, create_connection: 'type[ClientConnection] | None' = None, **kwargs: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__ = __await__(self) -> 'Generator[Any, None, ClientConnection]'
|
| async create_connection(self) -> 'ClientConnection'
| Create TCP or Unix connection.
|
| process_redirect(self, exc: 'Exception') -> 'Exception | str'
| Determine whether a connection error is a redirect that can be followed.
|
| Return the new URI if it's a valid redirect. Else, return an exception.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.framing
Python Library Documentation: module websockets.legacy.framing in websockets.legacy
NAME
websockets.legacy.framing
CLASSES
builtins.tuple(builtins.object)
Frame
class Frame(builtins.tuple)
| Frame(fin: ForwardRef('bool'), opcode: ForwardRef('frames.Opcode'), data: ForwardRef('bytes'), rsv1: ForwardRef('bool') = False, rsv2: ForwardRef('bool') = False, rsv3: ForwardRef('bool') = False)
|
| Frame(fin, opcode, data, rsv1, rsv2, rsv3)
|
| Method resolution order:
| Frame
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __getnewargs__(self) from collections.Frame
| Return self as a plain tuple. Used by copy and pickle.
|
| __repr__(self) from collections.Frame
| Return a nicely formatted representation string
|
| __str__(self) -> 'str'
| Return str(self).
|
| _asdict(self) from collections.Frame
| Return a new dict which maps field names to their values.
|
| _replace(self, /, **kwds) from collections.Frame
| Return a new Frame object replacing specified fields with new values
|
| check(self) -> 'None'
|
| write(self, write: 'Callable[[bytes], Any]', *, mask: 'bool', extensions: 'Sequence[extensions.Extension] | None' = None) -> 'None'
| Write a WebSocket frame.
|
| Args:
| frame: Frame to write.
| write: Function that writes bytes.
| mask: Whether the frame should be masked i.e. whether the write
| happens on the client side.
| extensions: List of extensions, applied in order.
|
| Raises:
| ProtocolError: If the frame contains incorrect values.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| _make(iterable) from collections.Frame
| Make a new Frame object from a sequence or iterable
|
| async read(reader: 'Callable[[int], Awaitable[bytes]]', *, mask: 'bool', max_size: 'int | None' = None, extensions: 'Sequence[extensions.Extension] | None' = None) -> 'Frame'
| Read a WebSocket frame.
|
| Args:
| reader: Coroutine that reads exactly the requested number of
| bytes, unless the end of file is reached.
| mask: Whether the frame should be masked i.e. whether the read
| happens on the server side.
| max_size: Maximum payload size in bytes.
| extensions: List of extensions, applied in reverse order.
|
| Raises:
| PayloadTooBig: If the frame exceeds ``max_size``.
| ProtocolError: If the frame contains incorrect values.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(_cls, fin: ForwardRef('bool'), opcode: ForwardRef('frames.Opcode'), data: ForwardRef('bytes'), rsv1: ForwardRef('bool') = False, rsv2: ForwardRef('bool') = False, rsv3: ForwardRef('bool') = False) from namedtuple_Frame.Frame
| Create new instance of Frame(fin, opcode, data, rsv1, rsv2, rsv3)
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| new_frame
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| fin
| Alias for field number 0
|
| opcode
| Alias for field number 1
|
| data
| Alias for field number 2
|
| rsv1
| Alias for field number 3
|
| rsv2
| Alias for field number 4
|
| rsv3
| Alias for field number 5
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'data': ForwardRef('bytes'), 'fin': ForwardRef('boo...
|
| __match_args__ = ('fin', 'opcode', 'data', 'rsv1', 'rsv2', 'rsv3')
|
| __orig_bases__ = (<function NamedTuple>,)
|
| _field_defaults = {'rsv1': False, 'rsv2': False, 'rsv3': False}
|
| _fields = ('fin', 'opcode', 'data', 'rsv1', 'rsv2', 'rsv3')
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...)
| See PEP 585
FUNCTIONS
apply_mask(...)
Apply masking to the data of a WebSocket message.
encode_data = prepare_ctrl(data: 'Data') -> 'bytes'
Convert a string or byte-like object to bytes.
This function is designed for ping and pong frames.
If ``data`` is a :class:`str`, return a :class:`bytes` object encoding
``data`` in UTF-8.
If ``data`` is a bytes-like object, return a :class:`bytes` object.
Raises:
TypeError: If ``data`` doesn't have a supported type.
parse_close(data: 'bytes') -> 'tuple[int, str]'
Parse the payload from a close frame.
Returns:
Close code and reason.
Raises:
ProtocolError: If data is ill-formed.
UnicodeDecodeError: If the reason isn't valid UTF-8.
prepare_ctrl(data: 'Data') -> 'bytes'
Convert a string or byte-like object to bytes.
This function is designed for ping and pong frames.
If ``data`` is a :class:`str`, return a :class:`bytes` object encoding
``data`` in UTF-8.
If ``data`` is a bytes-like object, return a :class:`bytes` object.
Raises:
TypeError: If ``data`` doesn't have a supported type.
prepare_data(data: 'Data') -> 'tuple[int, bytes]'
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 :class:`str`, return ``OP_TEXT`` and a :class:`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.
serialize_close(code: 'int', reason: 'str') -> 'bytes'
Serialize the payload for a close frame.
DATA
BytesLike = (<class 'bytes'>, <class 'bytearray'>, <class 'memoryview'...
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
Data = typing.Union[str, bytes]
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\websockets\legacy\framing.py
websockets.handshake
Python Library Documentation: module websockets.legacy.handshake in websockets.legacy
NAME
websockets.legacy.handshake
FUNCTIONS
build_request(headers: 'Headers') -> 'str'
Build a handshake request to send to the server.
Update request headers passed in argument.
Args:
headers: Handshake request headers.
Returns:
``key`` that must be passed to :func:`check_response`.
build_response(headers: 'Headers', key: 'str') -> 'None'
Build a handshake response to send to the client.
Update response headers passed in argument.
Args:
headers: Handshake response headers.
key: Returned by :func:`check_request`.
check_request(headers: 'Headers') -> 'str'
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.
Args:
headers: Handshake request headers.
Returns:
``key`` that must be passed to :func:`build_response`.
Raises:
InvalidHandshake: If the handshake request is invalid.
Then, the server must return a 400 Bad Request error.
check_response(headers: 'Headers', key: 'str') -> 'None'
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.
Args:
headers: Handshake response headers.
key: Returned by :func:`build_request`.
Raises:
InvalidHandshake: If the handshake response is invalid.
DATA
__all__ = ['build_request', 'check_request', 'build_response', 'check_...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\websockets\legacy\handshake.py
websockets.imports
Python Library Documentation: module websockets.imports in websockets
NAME
websockets.imports
FUNCTIONS
lazy_import(namespace: 'dict[str, Any]', aliases: 'dict[str, str] | None' = None, deprecated_aliases: 'dict[str, str] | None' = None) -> 'None'
Provide lazy, module-level imports.
Typical use::
__getattr__, __dir__ = lazy_import(
globals(),
aliases={
"<name>": "<source module>",
...
},
deprecated_aliases={
...,
}
)
This function defines ``__getattr__`` and ``__dir__`` per :pep:`562`.
DATA
__all__ = ['lazy_import']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\websockets\imports.py
websockets.lazy_import
Python Library Documentation: function lazy_import in module websockets.imports
lazy_import(namespace: 'dict[str, Any]', aliases: 'dict[str, str] | None' = None, deprecated_aliases: 'dict[str, str] | None' = None) -> 'None'
Provide lazy, module-level imports.
Typical use::
__getattr__, __dir__ = lazy_import(
globals(),
aliases={
"<name>": "<source module>",
...
},
deprecated_aliases={
...,
}
)
This function defines ``__getattr__`` and ``__dir__`` per :pep:`562`.
websockets.parse_uri
Python Library Documentation: function parse_uri in module websockets.uri
parse_uri(uri: 'str') -> 'WebSocketURI'
Parse and validate a WebSocket URI.
Args:
uri: WebSocket URI.
Returns:
Parsed WebSocket URI.
Raises:
InvalidURI: If ``uri`` isn't a valid WebSocket URI.
websockets.route
Python Library Documentation: function route in module websockets.asyncio.router
route(url_map: 'Map', *args: 'Any', server_name: 'str | None' = None, ssl: 'ssl_module.SSLContext | Literal[True] | None' = None, create_router: 'type[Router] | None' = None, **kwargs: 'Any') -> 'Awaitable[Server]'
Create a WebSocket server dispatching connections to different handlers.
This feature requires the third-party library `werkzeug`_:
.. code-block:: console
$ pip install werkzeug
.. _werkzeug: https://werkzeug.palletsprojects.com/
:func:`route` accepts the same arguments as
:func:`~websockets.sync.server.serve`, except as described below.
The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns
to connection handlers. In addition to the connection, handlers receive
parameters captured in the URL as keyword arguments.
Here's an example::
from websockets.asyncio.router import route
from werkzeug.routing import Map, Rule
async def channel_handler(websocket, channel_id):
...
url_map = Map([
Rule("/channel/<uuid:channel_id>", endpoint=channel_handler),
...
])
# set this future to exit the server
stop = asyncio.get_running_loop().create_future()
async with route(url_map, ...) as server:
await stop
Refer to the documentation of :mod:`werkzeug.routing` for details.
If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map,
when the server runs behind a reverse proxy that modifies the ``Host``
header or terminates TLS, you need additional configuration:
* Set ``server_name`` to the name of the server as seen by clients. When not
provided, websockets uses the value of the ``Host`` header.
* Set ``ssl=True`` to generate ``wss://`` URIs without actually enabling
TLS. Under the hood, this bind the URL map with a ``url_scheme`` of
``wss://`` instead of ``ws://``.
There is no need to specify ``websocket=True`` in each rule. It is added
automatically.
Args:
url_map: Mapping of URL patterns to connection handlers.
server_name: Name of the server as seen by clients. If :obj:`None`,
websockets uses the value of the ``Host`` header.
ssl: Configuration for enabling TLS on the connection. Set it to
:obj:`True` if a reverse proxy terminates TLS connections.
create_router: Factory for the :class:`Router` dispatching requests to
handlers. Set it to a wrapper or a subclass to customize routing.
websockets.serve
Python Library Documentation: class serve in module websockets.asyncio.server
class serve(builtins.object)
| serve(handler: 'Callable[[ServerConnection], Awaitable[None]]', host: 'str | None' = None, port: 'int | None' = None, *, origins: 'Sequence[Origin | re.Pattern[str] | None] | None' = None, extensions: 'Sequence[ServerExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, select_subprotocol: 'Callable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | None' = None, compression: 'str | None' = 'deflate', process_request: 'Callable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | None' = None, process_response: 'Callable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | None' = None, server_header: 'str | None' = 'Python/3.12 websockets/15.0.1', open_timeout: 'float | None' = 10, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_size: 'int | None' = 1048576, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768, logger: 'LoggerLike | None' = None, create_connection: 'type[ServerConnection] | None' = None, **kwargs: 'Any') -> 'None'
|
| Create a WebSocket server listening on ``host`` and ``port``.
|
| Whenever a client connects, the server creates a :class:`ServerConnection`,
| performs the opening handshake, and delegates to the ``handler`` coroutine.
|
| The handler receives the :class:`ServerConnection` instance, which you can
| use to send and receive messages.
|
| Once the handler completes, either normally or with an exception, the server
| performs the closing handshake and closes the connection.
|
| This coroutine returns a :class:`Server` whose API mirrors
| :class:`asyncio.Server`. Treat it as an asynchronous context manager to
| ensure that the server will be closed::
|
| from websockets.asyncio.server import serve
|
| def handler(websocket):
| ...
|
| # set this future to exit the server
| stop = asyncio.get_running_loop().create_future()
|
| async with serve(handler, host, port):
| await stop
|
| Alternatively, call :meth:`~Server.serve_forever` to serve requests and
| cancel it to stop the server::
|
| server = await serve(handler, host, port)
| await server.serve_forever()
|
| Args:
| handler: Connection handler. It receives the WebSocket connection,
| which is a :class:`ServerConnection`, in argument.
| host: Network interfaces the server binds to.
| See :meth:`~asyncio.loop.create_server` for details.
| port: TCP port the server listens on.
| See :meth:`~asyncio.loop.create_server` for details.
| origins: Acceptable values of the ``Origin`` header, for defending
| against Cross-Site WebSocket Hijacking attacks. Values can be
| :class:`str` to test for an exact match or regular expressions
| compiled by :func:`re.compile` to test against a pattern. Include
| :obj:`None` in the list if the lack of an origin is acceptable.
| extensions: List of supported extensions, in order in which they
| should be negotiated and run.
| subprotocols: List of supported subprotocols, in order of decreasing
| preference.
| select_subprotocol: Callback for selecting a subprotocol among
| those supported by the client and the server. It receives a
| :class:`ServerConnection` (not a
| :class:`~websockets.server.ServerProtocol`!) instance and a list of
| subprotocols offered by the client. Other than the first argument,
| it has the same behavior as the
| :meth:`ServerProtocol.select_subprotocol
| <websockets.server.ServerProtocol.select_subprotocol>` method.
| compression: The "permessage-deflate" extension is enabled by default.
| Set ``compression`` to :obj:`None` to disable it. See the
| :doc:`compression guide <../../topics/compression>` for details.
| process_request: Intercept the request during the opening handshake.
| Return an HTTP response to force the response or :obj:`None` to
| continue normally. When you force an HTTP 101 Continue response, the
| handshake is successful. Else, the connection is aborted.
| ``process_request`` may be a function or a coroutine.
| process_response: Intercept the response during the opening handshake.
| Return an HTTP response to force the response or :obj:`None` to
| continue normally. When you force an HTTP 101 Continue response, the
| handshake is successful. Else, the connection is aborted.
| ``process_response`` may be a function or a coroutine.
| server_header: Value of the ``Server`` response header.
| It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
| :obj:`None` removes the header.
| open_timeout: Timeout for opening connections in seconds.
| :obj:`None` disables the timeout.
| ping_interval: Interval between keepalive pings in seconds.
| :obj:`None` disables keepalive.
| ping_timeout: Timeout for keepalive pings in seconds.
| :obj:`None` disables timeouts.
| close_timeout: Timeout for closing connections in seconds.
| :obj:`None` disables the timeout.
| max_size: Maximum size of incoming messages in bytes.
| :obj:`None` disables the limit.
| max_queue: High-water mark of the buffer where frames are received.
| It defaults to 16 frames. The low-water mark defaults to ``max_queue
| // 4``. You may pass a ``(high, low)`` tuple to set the high-water
| and low-water marks. If you want to disable flow control entirely,
| you may set it to ``None``, although that's a bad idea.
| write_limit: High-water mark of write buffer in bytes. It is passed to
| :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults
| to 32 KiB. You may pass a ``(high, low)`` tuple to set the
| high-water and low-water marks.
| logger: Logger for this server.
| It defaults to ``logging.getLogger("websockets.server")``. See the
| :doc:`logging guide <../../topics/logging>` for details.
| create_connection: Factory for the :class:`ServerConnection` managing
| the connection. Set it to a wrapper or a subclass to customize
| connection handling.
|
| Any other keyword arguments are passed to the event loop's
| :meth:`~asyncio.loop.create_server` method.
|
| For example:
|
| * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.
|
| * You can set ``sock`` to provide a preexisting TCP socket. You may call
| :func:`socket.create_server` (not to be confused with the event loop's
| :meth:`~asyncio.loop.create_server` method) to create a suitable server
| socket and customize it.
|
| * You can set ``start_serving`` to ``False`` to start accepting connections
| only after you call :meth:`~Server.start_serving()` or
| :meth:`~Server.serve_forever()`.
|
| Methods defined here:
|
| async __aenter__(self) -> 'Server'
|
| async __aexit__(self, exc_type: 'type[BaseException] | None', exc_value: 'BaseException | None', traceback: 'TracebackType | None') -> 'None'
|
| __await__(self) -> 'Generator[Any, None, Server]'
|
| async __await_impl__(self) -> 'Server'
|
| __init__(self, handler: 'Callable[[ServerConnection], Awaitable[None]]', host: 'str | None' = None, port: 'int | None' = None, *, origins: 'Sequence[Origin | re.Pattern[str] | None] | None' = None, extensions: 'Sequence[ServerExtensionFactory] | None' = None, subprotocols: 'Sequence[Subprotocol] | None' = None, select_subprotocol: 'Callable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | None' = None, compression: 'str | None' = 'deflate', process_request: 'Callable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | None' = None, process_response: 'Callable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | None' = None, server_header: 'str | None' = 'Python/3.12 websockets/15.0.1', open_timeout: 'float | None' = 10, ping_interval: 'float | None' = 20, ping_timeout: 'float | None' = 20, close_timeout: 'float | None' = 10, max_size: 'int | None' = 1048576, max_queue: 'int | None | tuple[int | None, int | None]' = 16, write_limit: 'int | tuple[int, int | None]' = 32768, logger: 'LoggerLike | None' = None, create_connection: 'type[ServerConnection] | None' = None, **kwargs: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__ = __await__(self) -> 'Generator[Any, None, Server]'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
websockets.unix_connect
Python Library Documentation: function unix_connect in module websockets.asyncio.client
unix_connect(path: 'str | None' = None, uri: 'str | None' = None, **kwargs: 'Any') -> 'connect'
Connect to a WebSocket server listening on a Unix socket.
This function accepts the same keyword arguments as :func:`connect`.
It's only available on Unix.
It's mainly useful for debugging servers listening on Unix sockets.
Args:
path: File system path to the Unix socket.
uri: URI of the WebSocket server. ``uri`` defaults to
``ws://localhost/`` or, when a ``ssl`` argument is provided, to
``wss://localhost/``.
websockets.unix_route
Python Library Documentation: function unix_route in module websockets.asyncio.router
unix_route(url_map: 'Map', path: 'str | None' = None, **kwargs: 'Any') -> 'Awaitable[Server]'
Create a WebSocket Unix server dispatching connections to different handlers.
:func:`unix_route` combines the behaviors of :func:`route` and
:func:`~websockets.asyncio.server.unix_serve`.
Args:
url_map: Mapping of URL patterns to connection handlers.
path: File system path to the Unix socket.
websockets.unix_serve
Python Library Documentation: function unix_serve in module websockets.asyncio.server
unix_serve(handler: 'Callable[[ServerConnection], Awaitable[None]]', path: 'str | None' = None, **kwargs: 'Any') -> 'Awaitable[Server]'
Create a WebSocket server listening on a Unix socket.
This function is identical to :func:`serve`, except the ``host`` and
``port`` arguments are replaced by ``path``. It's only available on Unix.
It's useful for deploying a server behind a reverse proxy such as nginx.
Args:
handler: Connection handler. It receives the WebSocket connection,
which is a :class:`ServerConnection`, in argument.
path: File system path to the Unix socket.
websockets.version
Python Library Documentation: module websockets.version in websockets
NAME
websockets.version
DATA
__all__ = ['tag', 'version', 'commit']
commit = '15.0.1'
tag = '15.0.1'
version = '15.0.1'
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\websockets\version.py