Skip to content

Commit b05fa2c

Browse files
committed
Rename WebSocketServer to Server.
The shorter name is better. Representation remains unambiguous: <websockets.asyncio.server.Server object at 0x...> The change isn't applied to the legacy implementation because it has longer names for other API too.
1 parent 2a17e1d commit b05fa2c

File tree

11 files changed

+77
-53
lines changed

11 files changed

+77
-53
lines changed

docs/faq/server.rst

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -313,8 +313,7 @@ Here's an example that terminates cleanly when it receives SIGTERM on Unix:
313313
How do I stop a server while keeping existing connections open?
314314
---------------------------------------------------------------
315315

316-
Call the server's :meth:`~WebSocketServer.close` method with
317-
``close_connections=False``.
316+
Call the server's :meth:`~Server.close` method with ``close_connections=False``.
318317

319318
Here's how to adapt the example just above::
320319

docs/howto/upgrade.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ Server APIs
154154
| ``websockets.server.unix_serve()`` |br| | |
155155
| :func:`websockets.legacy.server.unix_serve` | |
156156
+-------------------------------------------------------------------+-----------------------------------------------------+
157-
| ``websockets.WebSocketServer`` |br| | :class:`websockets.asyncio.server.WebSocketServer` |
157+
| ``websockets.WebSocketServer`` |br| | :class:`websockets.asyncio.server.Server` |
158158
| ``websockets.server.WebSocketServer`` |br| | |
159159
| :class:`websockets.legacy.server.WebSocketServer` | |
160160
+-------------------------------------------------------------------+-----------------------------------------------------+

docs/project/changelog.rst

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,6 @@ notice.
3535
Backwards-incompatible changes
3636
..............................
3737

38-
.. admonition:: The ``ssl_context`` argument of :func:`~sync.client.connect`
39-
and :func:`~sync.server.serve` in the :mod:`threading` implementation is
40-
renamed to ``ssl``.
41-
:class: note
42-
43-
This aligns the API of the :mod:`threading` implementation with the
44-
:mod:`asyncio` implementation.
45-
46-
For backwards compatibility, ``ssl_context`` is still supported.
47-
4838
.. admonition:: Receiving the request path in the second parameter of connection
4939
handlers is deprecated.
5040
:class: note
@@ -60,6 +50,26 @@ Backwards-incompatible changes
6050
path = request.path # only if handler() uses the path argument
6151
...
6252

53+
.. admonition:: The ``ssl_context`` argument of :func:`~sync.client.connect`
54+
and :func:`~sync.server.serve` in the :mod:`threading` implementation is
55+
renamed to ``ssl``.
56+
:class: note
57+
58+
This aligns the API of the :mod:`threading` implementation with the
59+
:mod:`asyncio` implementation.
60+
61+
For backwards compatibility, ``ssl_context`` is still supported.
62+
63+
.. admonition:: The ``WebSocketServer`` class in the :mod:`threading`
64+
implementation is renamed to :class:`~sync.server.Server`.
65+
:class: note
66+
67+
This class isn't designed to be imported or instantiated directly.
68+
:func:`~sync.server.serve` returns an instance. For this reason,
69+
the change should be transparent.
70+
71+
Regardless, an alias provides backwards compatibility.
72+
6373
New features
6474
............
6575

docs/reference/asyncio/server.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Creating a server
1515
Running a server
1616
----------------
1717

18-
.. autoclass:: WebSocketServer
18+
.. autoclass:: Server
1919

2020
.. automethod:: close
2121

docs/reference/sync/server.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ Creating a server
1313
Running a server
1414
----------------
1515

16-
.. autoclass:: WebSocketServer
16+
.. autoclass:: Server
1717

1818
.. automethod:: serve_forever
1919

src/websockets/asyncio/server.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from .connection import Connection, broadcast
2929

3030

31-
__all__ = ["broadcast", "serve", "unix_serve", "ServerConnection", "WebSocketServer"]
31+
__all__ = ["broadcast", "serve", "unix_serve", "ServerConnection", "Server"]
3232

3333

3434
class ServerConnection(Connection):
@@ -60,7 +60,7 @@ class ServerConnection(Connection):
6060
def __init__(
6161
self,
6262
protocol: ServerProtocol,
63-
server: WebSocketServer,
63+
server: Server,
6464
*,
6565
ping_interval: float | None = 20,
6666
ping_timeout: float | None = 20,
@@ -223,11 +223,11 @@ def connection_lost(self, exc: Exception | None) -> None:
223223
self.request_rcvd.set_result(None)
224224

225225

226-
class WebSocketServer:
226+
class Server:
227227
"""
228228
WebSocket server returned by :func:`serve`.
229229
230-
This class mirrors the API of :class:`~asyncio.Server`.
230+
This class mirrors the API of :class:`asyncio.Server`.
231231
232232
It keeps track of WebSocket connections in order to close them properly
233233
when shutting down.
@@ -299,16 +299,16 @@ def __init__(
299299

300300
def wrap(self, server: asyncio.Server) -> None:
301301
"""
302-
Attach to a given :class:`~asyncio.Server`.
302+
Attach to a given :class:`asyncio.Server`.
303303
304304
Since :meth:`~asyncio.loop.create_server` doesn't support injecting a
305305
custom ``Server`` class, the easiest solution that doesn't rely on
306306
private :mod:`asyncio` APIs is to:
307307
308-
- instantiate a :class:`WebSocketServer`
308+
- instantiate a :class:`Server`
309309
- give the protocol factory a reference to that instance
310310
- call :meth:`~asyncio.loop.create_server` with the factory
311-
- attach the resulting :class:`~asyncio.Server` with this method
311+
- attach the resulting :class:`asyncio.Server` with this method
312312
313313
"""
314314
self.server = server
@@ -378,7 +378,7 @@ def close(self, close_connections: bool = True) -> None:
378378
"""
379379
Close the server.
380380
381-
* Close the underlying :class:`~asyncio.Server`.
381+
* Close the underlying :class:`asyncio.Server`.
382382
* When ``close_connections`` is :obj:`True`, which is the default,
383383
close existing connections. Specifically:
384384
@@ -402,7 +402,7 @@ async def _close(self, close_connections: bool) -> None:
402402
Implementation of :meth:`close`.
403403
404404
This calls :meth:`~asyncio.Server.close` on the underlying
405-
:class:`~asyncio.Server` object to stop accepting new connections and
405+
:class:`asyncio.Server` object to stop accepting new connections and
406406
then closes open connections with close code 1001.
407407
408408
"""
@@ -516,7 +516,7 @@ def sockets(self) -> Iterable[socket.socket]:
516516
"""
517517
return self.server.sockets
518518

519-
async def __aenter__(self) -> WebSocketServer: # pragma: no cover
519+
async def __aenter__(self) -> Server: # pragma: no cover
520520
return self
521521

522522
async def __aexit__(
@@ -543,8 +543,8 @@ class serve:
543543
Once the handler completes, either normally or with an exception, the server
544544
performs the closing handshake and closes the connection.
545545
546-
This coroutine returns a :class:`WebSocketServer` whose API mirrors
547-
:class:`~asyncio.Server`. Treat it as an asynchronous context manager to
546+
This coroutine returns a :class:`Server` whose API mirrors
547+
:class:`asyncio.Server`. Treat it as an asynchronous context manager to
548548
ensure that the server will be closed::
549549
550550
def handler(websocket):
@@ -556,8 +556,8 @@ def handler(websocket):
556556
async with websockets.asyncio.server.serve(handler, host, port):
557557
await stop
558558
559-
Alternatively, call :meth:`~WebSocketServer.serve_forever` to serve requests
560-
and cancel it to stop the server::
559+
Alternatively, call :meth:`~Server.serve_forever` to serve requests and
560+
cancel it to stop the server::
561561
562562
server = await websockets.asyncio.server.serve(handler, host, port)
563563
await server.serve_forever()
@@ -638,8 +638,8 @@ def handler(websocket):
638638
socket and customize it.
639639
640640
* You can set ``start_serving`` to ``False`` to start accepting connections
641-
only after you call :meth:`~WebSocketServer.start_serving()` or
642-
:meth:`~WebSocketServer.serve_forever()`.
641+
only after you call :meth:`~Server.start_serving()` or
642+
:meth:`~Server.serve_forever()`.
643643
644644
"""
645645

@@ -704,7 +704,7 @@ def __init__(
704704
if create_connection is None:
705705
create_connection = ServerConnection
706706

707-
self.server = WebSocketServer(
707+
self.server = Server(
708708
handler,
709709
process_request=process_request,
710710
process_response=process_response,
@@ -773,7 +773,7 @@ def protocol_select_subprotocol(
773773

774774
# async with serve(...) as ...: ...
775775

776-
async def __aenter__(self) -> WebSocketServer:
776+
async def __aenter__(self) -> Server:
777777
return await self
778778

779779
async def __aexit__(
@@ -787,11 +787,11 @@ async def __aexit__(
787787

788788
# ... = await serve(...)
789789

790-
def __await__(self) -> Generator[Any, None, WebSocketServer]:
790+
def __await__(self) -> Generator[Any, None, Server]:
791791
# Create a suitable iterator by calling __await__ on a coroutine.
792792
return self.__await_impl__().__await__()
793793

794-
async def __await_impl__(self) -> WebSocketServer:
794+
async def __await_impl__(self) -> Server:
795795
server = await self._create_server
796796
self.server.wrap(server)
797797
return self.server
@@ -805,7 +805,7 @@ def unix_serve(
805805
handler: Callable[[ServerConnection], Awaitable[None]],
806806
path: str | None = None,
807807
**kwargs: Any,
808-
) -> Awaitable[WebSocketServer]:
808+
) -> Awaitable[Server]:
809809
"""
810810
Create a WebSocket server listening on a Unix socket.
811811

src/websockets/sync/server.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from .utils import Deadline
2525

2626

27-
__all__ = ["serve", "unix_serve", "ServerConnection", "WebSocketServer"]
27+
__all__ = ["serve", "unix_serve", "ServerConnection", "Server"]
2828

2929

3030
class ServerConnection(Connection):
@@ -196,7 +196,7 @@ def recv_events(self) -> None:
196196
self.request_rcvd.set()
197197

198198

199-
class WebSocketServer:
199+
class Server:
200200
"""
201201
WebSocket server returned by :func:`serve`.
202202
@@ -283,7 +283,7 @@ def fileno(self) -> int:
283283
"""
284284
return self.socket.fileno()
285285

286-
def __enter__(self) -> WebSocketServer:
286+
def __enter__(self) -> Server:
287287
return self
288288

289289
def __exit__(
@@ -295,6 +295,16 @@ def __exit__(
295295
self.shutdown()
296296

297297

298+
def __getattr__(name: str) -> Any:
299+
if name == "WebSocketServer":
300+
warnings.warn(
301+
"WebSocketServer was renamed to Server",
302+
DeprecationWarning,
303+
)
304+
return Server
305+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
306+
307+
298308
def serve(
299309
handler: Callable[[ServerConnection], None],
300310
host: str | None = None,
@@ -340,7 +350,7 @@ def serve(
340350
# Escape hatch for advanced customization
341351
create_connection: type[ServerConnection] | None = None,
342352
**kwargs: Any,
343-
) -> WebSocketServer:
353+
) -> Server:
344354
"""
345355
Create a WebSocket server listening on ``host`` and ``port``.
346356
@@ -353,10 +363,10 @@ def serve(
353363
Once the handler completes, either normally or with an exception, the server
354364
performs the closing handshake and closes the connection.
355365
356-
This function returns a :class:`WebSocketServer` whose API mirrors
366+
This function returns a :class:`Server` whose API mirrors
357367
:class:`~socketserver.BaseServer`. Treat it as a context manager to ensure
358-
that it will be closed and call :meth:`~WebSocketServer.serve_forever` to
359-
serve requests::
368+
that it will be closed and call :meth:`~Server.serve_forever` to serve
369+
requests::
360370
361371
def handler(websocket):
362372
...
@@ -552,14 +562,14 @@ def protocol_select_subprotocol(
552562

553563
# Initialize server
554564

555-
return WebSocketServer(sock, conn_handler, logger)
565+
return Server(sock, conn_handler, logger)
556566

557567

558568
def unix_serve(
559569
handler: Callable[[ServerConnection], None],
560570
path: str | None = None,
561571
**kwargs: Any,
562-
) -> WebSocketServer:
572+
) -> Server:
563573
"""
564574
Create a WebSocket server listening on a Unix socket.
565575

tests/asyncio/client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import contextlib
22

33
from websockets.asyncio.client import *
4-
from websockets.asyncio.server import WebSocketServer
4+
from websockets.asyncio.server import Server
55

66
from .server import get_server_host_port
77

@@ -17,7 +17,7 @@ async def run_client(wsuri_or_server, secure=None, resource_name="/", **kwargs):
1717
if isinstance(wsuri_or_server, str):
1818
wsuri = wsuri_or_server
1919
else:
20-
assert isinstance(wsuri_or_server, WebSocketServer)
20+
assert isinstance(wsuri_or_server, Server)
2121
if secure is None:
2222
secure = "ssl" in kwargs
2323
protocol = "wss" if secure else "ws"

tests/asyncio/test_server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,7 @@ async def test_unsupported_compression(self):
535535

536536
class WebSocketServerTests(unittest.IsolatedAsyncioTestCase):
537537
async def test_logger(self):
538-
"""WebSocketServer accepts a logger argument."""
538+
"""Server accepts a logger argument."""
539539
logger = logging.getLogger("test")
540540
async with run_server(logger=logger) as server:
541541
self.assertIs(server.logger, logger)

tests/sync/client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import contextlib
22

33
from websockets.sync.client import *
4-
from websockets.sync.server import WebSocketServer
4+
from websockets.sync.server import Server
55

66

77
__all__ = [
@@ -15,7 +15,7 @@ def run_client(wsuri_or_server, secure=None, resource_name="/", **kwargs):
1515
if isinstance(wsuri_or_server, str):
1616
wsuri = wsuri_or_server
1717
else:
18-
assert isinstance(wsuri_or_server, WebSocketServer)
18+
assert isinstance(wsuri_or_server, Server)
1919
if secure is None:
2020
# Backwards compatibility: ssl used to be called ssl_context.
2121
secure = "ssl" in kwargs or "ssl_context" in kwargs

tests/sync/test_server.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -383,18 +383,18 @@ def test_unsupported_compression(self):
383383

384384
class WebSocketServerTests(unittest.TestCase):
385385
def test_logger(self):
386-
"""WebSocketServer accepts a logger argument."""
386+
"""Server accepts a logger argument."""
387387
logger = logging.getLogger("test")
388388
with run_server(logger=logger) as server:
389389
self.assertIs(server.logger, logger)
390390

391391
def test_fileno(self):
392-
"""WebSocketServer provides a fileno attribute."""
392+
"""Server provides a fileno attribute."""
393393
with run_server() as server:
394394
self.assertIsInstance(server.fileno(), int)
395395

396396
def test_shutdown(self):
397-
"""WebSocketServer provides a shutdown method."""
397+
"""Server provides a shutdown method."""
398398
with run_server() as server:
399399
server.shutdown()
400400
# Check that the server socket is closed.
@@ -409,3 +409,8 @@ def test_ssl_context_argument(self):
409409
with run_server(ssl_context=SERVER_CONTEXT) as server:
410410
with run_client(server, ssl=CLIENT_CONTEXT):
411411
pass
412+
413+
def test_web_socket_server_class(self):
414+
with self.assertDeprecationWarning("WebSocketServer was renamed to Server"):
415+
from websockets.sync.server import WebSocketServer
416+
self.assertIs(WebSocketServer, Server)

0 commit comments

Comments
 (0)