| 1 |
Upgrade to the new :mod:`asyncio` implementation |
| 2 |
================================================ |
| 3 |
|
| 4 |
.. currentmodule:: websockets |
| 5 |
|
| 6 |
The new :mod:`asyncio` implementation is the default since version 14.0. It is a |
| 7 |
full rewrite of the original implementation of websockets. |
| 8 |
|
| 9 |
It provides a very similar API. However, there are a few differences. |
| 10 |
|
| 11 |
The recommended upgrade process is: |
| 12 |
|
| 13 |
#. Make sure that your code doesn't use any `deprecated APIs`_. If it doesn't |
| 14 |
raise warnings, you're fine. |
| 15 |
#. `Update import paths`_. For straightforward use cases, this could be the only |
| 16 |
step you need to take. |
| 17 |
#. Check out `new features and improvements`_. Consider taking advantage of them |
| 18 |
in your code. |
| 19 |
#. Review `API changes`_. If needed, update your application to preserve its |
| 20 |
current behavior. |
| 21 |
|
| 22 |
In the interest of brevity, only :func:`~asyncio.client.connect` and |
| 23 |
:func:`~asyncio.server.serve` are discussed below but everything also applies |
| 24 |
to :func:`~asyncio.client.unix_connect` and :func:`~asyncio.server.unix_serve` |
| 25 |
respectively. |
| 26 |
|
| 27 |
.. admonition:: What will happen to the original implementation? |
| 28 |
:class: hint |
| 29 |
|
| 30 |
The original implementation is deprecated. It will be maintained for five |
| 31 |
years after deprecation, meaning until November 2029, according to the |
| 32 |
:ref:`backwards-compatibility policy <backwards-compatibility policy>`. |
| 33 |
Then, it will be removed. |
| 34 |
|
| 35 |
.. _deprecated APIs: |
| 36 |
|
| 37 |
Deprecated APIs |
| 38 |
--------------- |
| 39 |
|
| 40 |
Here's the list of deprecated behaviors that the original implementation still |
| 41 |
supports and that the new implementation doesn't reproduce. |
| 42 |
|
| 43 |
If you're seeing a :class:`DeprecationWarning`, follow upgrade instructions from |
| 44 |
the release notes of the version in which the feature was deprecated. |
| 45 |
|
| 46 |
* The ``path`` argument of connection handlers — unnecessary since :ref:`10.1` |
| 47 |
and deprecated in :ref:`13.0`. |
| 48 |
* The ``loop`` and ``legacy_recv`` arguments of :func:`~legacy.client.connect` |
| 49 |
and :func:`~legacy.server.serve`, which were removed — deprecated in |
| 50 |
:ref:`10.0`. |
| 51 |
* The ``timeout`` and ``klass`` arguments of :func:`~legacy.client.connect` and |
| 52 |
:func:`~legacy.server.serve`, which were renamed to ``close_timeout`` and |
| 53 |
``create_protocol`` — deprecated in :ref:`7.0` and :ref:`3.4` respectively. |
| 54 |
* An empty string in the ``origins`` argument of :func:`~legacy.server.serve` — |
| 55 |
deprecated in :ref:`7.0`. |
| 56 |
* The ``host``, ``port``, and ``secure`` attributes of connections — deprecated |
| 57 |
in :ref:`8.0`. |
| 58 |
|
| 59 |
.. _Update import paths: |
| 60 |
|
| 61 |
Import paths |
| 62 |
------------ |
| 63 |
|
| 64 |
For context, the ``websockets`` package is structured as follows: |
| 65 |
|
| 66 |
* The new implementation is found in the ``websockets.asyncio`` package. |
| 67 |
* The original implementation was moved to the ``websockets.legacy`` package |
| 68 |
and deprecated. |
| 69 |
* The ``websockets`` package provides aliases for convenience. They were |
| 70 |
switched to the new implementation in version 14.0 or deprecated when there |
| 71 |
wasn't an equivalent API. |
| 72 |
* The ``websockets.client`` and ``websockets.server`` packages provide aliases |
| 73 |
for backwards-compatibility with earlier versions of websockets. They were |
| 74 |
deprecated. |
| 75 |
|
| 76 |
To upgrade to the new :mod:`asyncio` implementation, change import paths as |
| 77 |
shown in the tables below. |
| 78 |
|
| 79 |
.. |br| raw:: html |
| 80 |
|
| 81 |
<br/> |
| 82 |
|
| 83 |
Client APIs |
| 84 |
........... |
| 85 |
|
| 86 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 87 |
| Legacy :mod:`asyncio` implementation | New :mod:`asyncio` implementation | |
| 88 |
+===================================================================+=====================================================+ |
| 89 |
| ``websockets.connect()`` *(before 14.0)* |br| | ``websockets.connect()`` *(since 14.0)* |br| | |
| 90 |
| ``websockets.client.connect()`` |br| | :func:`websockets.asyncio.client.connect` | |
| 91 |
| :func:`websockets.legacy.client.connect` | | |
| 92 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 93 |
| ``websockets.unix_connect()`` *(before 14.0)* |br| | ``websockets.unix_connect()`` *(since 14.0)* |br| | |
| 94 |
| ``websockets.client.unix_connect()`` |br| | :func:`websockets.asyncio.client.unix_connect` | |
| 95 |
| :func:`websockets.legacy.client.unix_connect` | | |
| 96 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 97 |
| ``websockets.WebSocketClientProtocol`` |br| | ``websockets.ClientConnection`` *(since 14.2)* |br| | |
| 98 |
| ``websockets.client.WebSocketClientProtocol`` |br| | :class:`websockets.asyncio.client.ClientConnection` | |
| 99 |
| :class:`websockets.legacy.client.WebSocketClientProtocol` | | |
| 100 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 101 |
|
| 102 |
Server APIs |
| 103 |
........... |
| 104 |
|
| 105 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 106 |
| Legacy :mod:`asyncio` implementation | New :mod:`asyncio` implementation | |
| 107 |
+===================================================================+=====================================================+ |
| 108 |
| ``websockets.serve()`` *(before 14.0)* |br| | ``websockets.serve()`` *(since 14.0)* |br| | |
| 109 |
| ``websockets.server.serve()`` |br| | :func:`websockets.asyncio.server.serve` | |
| 110 |
| :func:`websockets.legacy.server.serve` | | |
| 111 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 112 |
| ``websockets.unix_serve()`` *(before 14.0)* |br| | ``websockets.unix_serve()`` *(since 14.0)* |br| | |
| 113 |
| ``websockets.server.unix_serve()`` |br| | :func:`websockets.asyncio.server.unix_serve` | |
| 114 |
| :func:`websockets.legacy.server.unix_serve` | | |
| 115 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 116 |
| ``websockets.WebSocketServer`` |br| | ``websockets.Server`` *(since 14.2)* |br| | |
| 117 |
| ``websockets.server.WebSocketServer`` |br| | :class:`websockets.asyncio.server.Server` | |
| 118 |
| :class:`websockets.legacy.server.WebSocketServer` | | |
| 119 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 120 |
| ``websockets.WebSocketServerProtocol`` |br| | ``websockets.ServerConnection`` *(since 14.2)* |br| | |
| 121 |
| ``websockets.server.WebSocketServerProtocol`` |br| | :class:`websockets.asyncio.server.ServerConnection` | |
| 122 |
| :class:`websockets.legacy.server.WebSocketServerProtocol` | | |
| 123 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 124 |
| ``websockets.broadcast()`` *(before 14.0)* |br| | ``websockets.broadcast()`` *(since 14.0)* |br| | |
| 125 |
| :func:`websockets.legacy.server.broadcast()` | :func:`websockets.asyncio.server.broadcast` | |
| 126 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 127 |
| ``websockets.BasicAuthWebSocketServerProtocol`` |br| | See below :ref:`how to migrate <basic-auth>` to | |
| 128 |
| ``websockets.auth.BasicAuthWebSocketServerProtocol`` |br| | :func:`websockets.asyncio.server.basic_auth`. | |
| 129 |
| :class:`websockets.legacy.auth.BasicAuthWebSocketServerProtocol` | | |
| 130 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 131 |
| ``websockets.basic_auth_protocol_factory()`` |br| | See below :ref:`how to migrate <basic-auth>` to | |
| 132 |
| ``websockets.auth.basic_auth_protocol_factory()`` |br| | :func:`websockets.asyncio.server.basic_auth`. | |
| 133 |
| :func:`websockets.legacy.auth.basic_auth_protocol_factory` | | |
| 134 |
+-------------------------------------------------------------------+-----------------------------------------------------+ |
| 135 |
|
| 136 |
.. _new features and improvements: |
| 137 |
|
| 138 |
New features and improvements |
| 139 |
----------------------------- |
| 140 |
|
| 141 |
Customizing the opening handshake |
| 142 |
................................. |
| 143 |
|
| 144 |
On the server side, if you're customizing how :func:`~legacy.server.serve` |
| 145 |
processes the opening handshake with ``process_request``, ``extra_headers``, or |
| 146 |
``select_subprotocol``, you must update your code. Probably you can simplify it! |
| 147 |
|
| 148 |
``process_request`` and ``select_subprotocol`` have new signatures. |
| 149 |
``process_response`` replaces ``extra_headers`` and provides more flexibility. |
| 150 |
See process_request_, select_subprotocol_, and process_response_ below. |
| 151 |
|
| 152 |
Customizing automatic reconnection |
| 153 |
.................................. |
| 154 |
|
| 155 |
On the client side, if you're reconnecting automatically with ``async for ... in |
| 156 |
connect(...)``, the behavior when a connection attempt fails was enhanced and |
| 157 |
made configurable. |
| 158 |
|
| 159 |
The original implementation retried on any error. The new implementation uses an |
| 160 |
heuristic to determine whether an error is retryable or fatal. By default, only |
| 161 |
network errors and server errors (HTTP 500, 502, 503, or 504) are considered |
| 162 |
retryable. You can customize this behavior with the ``process_exception`` |
| 163 |
argument of :func:`~asyncio.client.connect`. |
| 164 |
|
| 165 |
See :func:`~client.process_exception` for more information. |
| 166 |
|
| 167 |
Here's how to revert to the behavior of the original implementation:: |
| 168 |
|
| 169 |
async for ... in connect(..., process_exception=lambda exc: exc): |
| 170 |
... |
| 171 |
|
| 172 |
Tracking open connections |
| 173 |
......................... |
| 174 |
|
| 175 |
The new implementation of :class:`~asyncio.server.Server` provides a |
| 176 |
:attr:`~asyncio.server.Server.connections` property, which is a set of all open |
| 177 |
connections. This didn't exist in the original implementation. |
| 178 |
|
| 179 |
If you're keeping track of open connections in order to broadcast messages to |
| 180 |
all of them, you can simplify your code by using this property. |
| 181 |
|
| 182 |
Controlling UTF-8 decoding |
| 183 |
.......................... |
| 184 |
|
| 185 |
The new implementation of the :meth:`~asyncio.connection.Connection.recv` method |
| 186 |
provides the ``decode`` argument to control UTF-8 decoding of messages. This |
| 187 |
didn't exist in the original implementation. |
| 188 |
|
| 189 |
If you're calling :meth:`~str.encode` on a :class:`str` object returned by |
| 190 |
:meth:`~asyncio.connection.Connection.recv`, using ``decode=False`` and removing |
| 191 |
:meth:`~str.encode` saves a round-trip of UTF-8 decoding and encoding for text |
| 192 |
messages. |
| 193 |
|
| 194 |
You can also force UTF-8 decoding of binary messages with ``decode=True``. This |
| 195 |
is rarely useful and has no performance benefits over decoding a :class:`bytes` |
| 196 |
object returned by :meth:`~asyncio.connection.Connection.recv`. |
| 197 |
|
| 198 |
Receiving fragmented messages |
| 199 |
............................. |
| 200 |
|
| 201 |
The new implementation provides the |
| 202 |
:meth:`~asyncio.connection.Connection.recv_streaming` method for receiving a |
| 203 |
fragmented message frame by frame. There was no way to do this in the original |
| 204 |
implementation. |
| 205 |
|
| 206 |
Depending on your use case, adopting this method may improve performance when |
| 207 |
streaming large messages. Specifically, it could reduce memory usage. |
| 208 |
|
| 209 |
.. _API changes: |
| 210 |
|
| 211 |
API changes |
| 212 |
----------- |
| 213 |
|
| 214 |
Attributes of connection objects |
| 215 |
................................ |
| 216 |
|
| 217 |
``path``, ``request_headers``, and ``response_headers`` |
| 218 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 219 |
|
| 220 |
The :attr:`~legacy.protocol.WebSocketCommonProtocol.path`, |
| 221 |
:attr:`~legacy.protocol.WebSocketCommonProtocol.request_headers` and |
| 222 |
:attr:`~legacy.protocol.WebSocketCommonProtocol.response_headers` properties are |
| 223 |
replaced by :attr:`~asyncio.connection.Connection.request` and |
| 224 |
:attr:`~asyncio.connection.Connection.response`. |
| 225 |
|
| 226 |
If your code uses them, you can update it as follows. |
| 227 |
|
| 228 |
========================================== ========================================== |
| 229 |
Legacy :mod:`asyncio` implementation New :mod:`asyncio` implementation |
| 230 |
========================================== ========================================== |
| 231 |
``connection.path`` ``connection.request.path`` |
| 232 |
``connection.request_headers`` ``connection.request.headers`` |
| 233 |
``connection.response_headers`` ``connection.response.headers`` |
| 234 |
========================================== ========================================== |
| 235 |
|
| 236 |
``open`` and ``closed`` |
| 237 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 238 |
|
| 239 |
The :attr:`~legacy.protocol.WebSocketCommonProtocol.open` and |
| 240 |
:attr:`~legacy.protocol.WebSocketCommonProtocol.closed` properties are removed. |
| 241 |
Using them was discouraged. |
| 242 |
|
| 243 |
Instead, you should call :meth:`~asyncio.connection.Connection.recv` or |
| 244 |
:meth:`~asyncio.connection.Connection.send` and handle |
| 245 |
:exc:`~exceptions.ConnectionClosed` exceptions. |
| 246 |
|
| 247 |
If your code uses them, you can update it as follows. |
| 248 |
|
| 249 |
========================================== ========================================== |
| 250 |
Legacy :mod:`asyncio` implementation New :mod:`asyncio` implementation |
| 251 |
========================================== ========================================== |
| 252 |
.. ``from websockets.protocol import State`` |
| 253 |
``connection.open`` ``connection.state is State.OPEN`` |
| 254 |
``connection.closed`` ``connection.state is State.CLOSED`` |
| 255 |
========================================== ========================================== |
| 256 |
|
| 257 |
Arguments of :func:`~asyncio.client.connect` |
| 258 |
............................................ |
| 259 |
|
| 260 |
``extra_headers`` → ``additional_headers`` |
| 261 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 262 |
|
| 263 |
If you're setting the ``User-Agent`` header with the ``extra_headers`` argument, |
| 264 |
you should set it with ``user_agent_header`` instead. |
| 265 |
|
| 266 |
If you're adding other headers to the handshake request sent by |
| 267 |
:func:`~legacy.client.connect` with ``extra_headers``, you must rename it to |
| 268 |
``additional_headers``. |
| 269 |
|
| 270 |
Arguments of :func:`~asyncio.server.serve` |
| 271 |
.......................................... |
| 272 |
|
| 273 |
``ws_handler`` → ``handler`` |
| 274 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 275 |
|
| 276 |
The first argument of :func:`~asyncio.server.serve` is now called ``handler`` |
| 277 |
instead of ``ws_handler``. It's usually passed as a positional argument, making |
| 278 |
this change transparent. If you're passing it as a keyword argument, you must |
| 279 |
update its name. |
| 280 |
|
| 281 |
.. _process_request: |
| 282 |
|
| 283 |
``process_request`` |
| 284 |
~~~~~~~~~~~~~~~~~~~ |
| 285 |
|
| 286 |
The signature of ``process_request`` changed. This is easiest to illustrate with |
| 287 |
an example:: |
| 288 |
|
| 289 |
import http |
| 290 |
|
| 291 |
# Original implementation |
| 292 |
|
| 293 |
def process_request(path, request_headers): |
| 294 |
return http.HTTPStatus.OK, [], b"OK\n" |
| 295 |
|
| 296 |
# New implementation |
| 297 |
|
| 298 |
def process_request(connection, request): |
| 299 |
return connection.respond(http.HTTPStatus.OK, "OK\n") |
| 300 |
|
| 301 |
serve(..., process_request=process_request, ...) |
| 302 |
|
| 303 |
``connection`` is always available in ``process_request``. In the original |
| 304 |
implementation, if you wanted to make the connection object available in a |
| 305 |
``process_request`` method, you had to write a subclass of |
| 306 |
:class:`~legacy.server.WebSocketServerProtocol` and pass it in the |
| 307 |
``create_protocol`` argument. This pattern isn't useful anymore; you can |
| 308 |
replace it with a ``process_request`` function or coroutine. |
| 309 |
|
| 310 |
``path`` and ``headers`` are available as attributes of the ``request`` object. |
| 311 |
|
| 312 |
.. _process_response: |
| 313 |
|
| 314 |
``extra_headers`` → ``process_response`` |
| 315 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 316 |
|
| 317 |
If you're setting the ``Server`` header with ``extra_headers``, you should set |
| 318 |
it with the ``server_header`` argument instead. |
| 319 |
|
| 320 |
If you're adding other headers to the handshake response sent by |
| 321 |
:func:`~legacy.server.serve` with the ``extra_headers`` argument, you must write |
| 322 |
a ``process_response`` callable instead. |
| 323 |
|
| 324 |
``process_request`` replaces ``extra_headers`` and provides more flexibility. |
| 325 |
In the most basic case, you would adapt your code as follows:: |
| 326 |
|
| 327 |
# Original implementation |
| 328 |
|
| 329 |
serve(..., extra_headers=HEADERS, ...) |
| 330 |
|
| 331 |
# New implementation |
| 332 |
|
| 333 |
def process_response(connection, request, response): |
| 334 |
response.headers.update(HEADERS) |
| 335 |
return response |
| 336 |
|
| 337 |
serve(..., process_response=process_response, ...) |
| 338 |
|
| 339 |
``connection`` is always available in ``process_response``, similar to |
| 340 |
``process_request``. In the original implementation, there was no way to make |
| 341 |
the connection object available. |
| 342 |
|
| 343 |
In addition, the ``request`` and ``response`` objects are available, which |
| 344 |
enables a broader range of use cases (e.g., logging) and makes |
| 345 |
``process_response`` more useful than ``extra_headers``. |
| 346 |
|
| 347 |
.. _select_subprotocol: |
| 348 |
|
| 349 |
``select_subprotocol`` |
| 350 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 351 |
|
| 352 |
If you're selecting a subprotocol, you must update your code because the |
| 353 |
signature of ``select_subprotocol`` changed. Here's an example:: |
| 354 |
|
| 355 |
# Original implementation |
| 356 |
|
| 357 |
def select_subprotocol(client_subprotocols, server_subprotocols): |
| 358 |
if "chat" in client_subprotocols: |
| 359 |
return "chat" |
| 360 |
|
| 361 |
# New implementation |
| 362 |
|
| 363 |
def select_subprotocol(connection, subprotocols): |
| 364 |
if "chat" in subprotocols |
| 365 |
return "chat" |
| 366 |
|
| 367 |
serve(..., select_subprotocol=select_subprotocol, ...) |
| 368 |
|
| 369 |
``connection`` is always available in ``select_subprotocol``. This brings the |
| 370 |
same benefits as in ``process_request``. It may remove the need to subclass |
| 371 |
:class:`~legacy.server.WebSocketServerProtocol`. |
| 372 |
|
| 373 |
The ``subprotocols`` argument contains the list of subprotocols offered by the |
| 374 |
client. The list of subprotocols supported by the server was removed because |
| 375 |
``select_subprotocols`` has to know which subprotocols it may select and under |
| 376 |
which conditions. |
| 377 |
|
| 378 |
Furthermore, the default behavior when ``select_subprotocol`` isn't provided |
| 379 |
changed in two ways: |
| 380 |
|
| 381 |
1. In the original implementation, a server with a list of subprotocols accepted |
| 382 |
to continue without a subprotocol. In the new implementation, a server that |
| 383 |
is configured with subprotocols rejects connections that don't support any. |
| 384 |
2. In the original implementation, when several subprotocols were available, the |
| 385 |
server averaged the client's preferences with its own preferences. In the new |
| 386 |
implementation, the server just picks the first subprotocol from its list. |
| 387 |
|
| 388 |
If you had a ``select_subprotocol`` for the sole purpose of rejecting |
| 389 |
connections without a subprotocol, you can remove it and keep only the |
| 390 |
``subprotocols`` argument. |
| 391 |
|
| 392 |
Arguments of :func:`~asyncio.client.connect` and :func:`~asyncio.server.serve` |
| 393 |
.............................................................................. |
| 394 |
|
| 395 |
``max_queue`` |
| 396 |
~~~~~~~~~~~~~ |
| 397 |
|
| 398 |
The ``max_queue`` argument of :func:`~asyncio.client.connect` and |
| 399 |
:func:`~asyncio.server.serve` has a new meaning but achieves a similar effect. |
| 400 |
|
| 401 |
It is now the high-water mark of a buffer of incoming frames. It defaults to 16 |
| 402 |
frames. It used to be the size of a buffer of incoming messages that refilled as |
| 403 |
soon as a message was read. It used to default to 32 messages. |
| 404 |
|
| 405 |
This can make a difference when messages are fragmented in several frames. In |
| 406 |
that case, you may want to increase ``max_queue``. |
| 407 |
|
| 408 |
If you're writing a high performance server and you know that you're receiving |
| 409 |
fragmented messages, probably you should adopt |
| 410 |
:meth:`~asyncio.connection.Connection.recv_streaming` and optimize the |
| 411 |
performance of reads again. |
| 412 |
|
| 413 |
In all other cases, given how uncommon fragmentation is, you shouldn't worry |
| 414 |
about this change. |
| 415 |
|
| 416 |
``read_limit`` |
| 417 |
~~~~~~~~~~~~~~ |
| 418 |
|
| 419 |
The ``read_limit`` argument doesn't exist in the new implementation because it |
| 420 |
doesn't buffer data received from the network in a |
| 421 |
:class:`~asyncio.StreamReader`. With a better design, this buffer could be |
| 422 |
removed. |
| 423 |
|
| 424 |
The buffer of incoming frames configured by ``max_queue`` is the only read |
| 425 |
buffer now. |
| 426 |
|
| 427 |
``write_limit`` |
| 428 |
~~~~~~~~~~~~~~~ |
| 429 |
|
| 430 |
The ``write_limit`` argument of :func:`~asyncio.client.connect` and |
| 431 |
:func:`~asyncio.server.serve` defaults to 32 KiB instead of 64 KiB. |
| 432 |
|
| 433 |
``create_protocol`` → ``create_connection`` |
| 434 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 435 |
|
| 436 |
The keyword argument of :func:`~asyncio.server.serve` for customizing the |
| 437 |
creation of the connection object is now called ``create_connection`` instead of |
| 438 |
``create_protocol``. It must return a :class:`~asyncio.server.ServerConnection` |
| 439 |
instead of a :class:`~legacy.server.WebSocketServerProtocol`. |
| 440 |
|
| 441 |
If you were customizing connection objects, probably you need to redo your |
| 442 |
customization. Consider switching to ``process_request`` and |
| 443 |
``select_subprotocol`` as their new design removes most use cases for |
| 444 |
``create_connection``. |
| 445 |
|
| 446 |
.. _basic-auth: |
| 447 |
|
| 448 |
Performing HTTP Basic Authentication |
| 449 |
.................................... |
| 450 |
|
| 451 |
.. admonition:: This section applies only to servers. |
| 452 |
:class: tip |
| 453 |
|
| 454 |
On the client side, :func:`~asyncio.client.connect` performs HTTP Basic |
| 455 |
Authentication automatically when the URI contains credentials. |
| 456 |
|
| 457 |
In the original implementation, the recommended way to add HTTP Basic |
| 458 |
Authentication to a server was to set the ``create_protocol`` argument of |
| 459 |
:func:`~legacy.server.serve` to a factory function generated by |
| 460 |
:func:`~legacy.auth.basic_auth_protocol_factory`:: |
| 461 |
|
| 462 |
from websockets.legacy.auth import basic_auth_protocol_factory |
| 463 |
from websockets.legacy.server import serve |
| 464 |
|
| 465 |
async with serve(..., create_protocol=basic_auth_protocol_factory(...)): |
| 466 |
... |
| 467 |
|
| 468 |
In the new implementation, the :func:`~asyncio.server.basic_auth` function |
| 469 |
generates a ``process_request`` coroutine that performs HTTP Basic |
| 470 |
Authentication:: |
| 471 |
|
| 472 |
from websockets.asyncio.server import basic_auth, serve |
| 473 |
|
| 474 |
async with serve(..., process_request=basic_auth(...)): |
| 475 |
... |
| 476 |
|
| 477 |
:func:`~asyncio.server.basic_auth` accepts either hard coded ``credentials`` or |
| 478 |
a ``check_credentials`` coroutine as well as an optional ``realm`` just like |
| 479 |
:func:`~legacy.auth.basic_auth_protocol_factory`. Furthermore, |
| 480 |
``check_credentials`` may be a function instead of a coroutine. |
| 481 |
|
| 482 |
This new API has more obvious semantics. That makes it easier to understand and |
| 483 |
also easier to extend. |
| 484 |
|
| 485 |
In the original implementation, overriding ``create_protocol`` changes the type |
| 486 |
of connection objects to :class:`~legacy.auth.BasicAuthWebSocketServerProtocol`, |
| 487 |
a subclass of :class:`~legacy.server.WebSocketServerProtocol` that performs HTTP |
| 488 |
Basic Authentication in its ``process_request`` method. |
| 489 |
|
| 490 |
To customize ``process_request`` further, you had only bad options: |
| 491 |
|
| 492 |
* the ill-defined option: add a ``process_request`` argument to |
| 493 |
:func:`~legacy.server.serve`; to tell which one would run first, you had to |
| 494 |
experiment or read the code; |
| 495 |
* the cumbersome option: subclass |
| 496 |
:class:`~legacy.auth.BasicAuthWebSocketServerProtocol`, then pass that |
| 497 |
subclass in the ``create_protocol`` argument of |
| 498 |
:func:`~legacy.auth.basic_auth_protocol_factory`. |
| 499 |
|
| 500 |
In the new implementation, you just write a ``process_request`` coroutine:: |
| 501 |
|
| 502 |
from websockets.asyncio.server import basic_auth, serve |
| 503 |
|
| 504 |
process_basic_auth = basic_auth(...) |
| 505 |
|
| 506 |
async def process_request(connection, request): |
| 507 |
... # some logic here |
| 508 |
response = await process_basic_auth(connection, request) |
| 509 |
if response is not None: |
| 510 |
return response |
| 511 |
... # more logic here |
| 512 |
|
| 513 |
async with serve(..., process_request=process_request): |
| 514 |
... |