Skip to content

Commit 5f28796

Browse files
committed
Add a router based on werkzeug.routing.
Fix #311.
1 parent 602d719 commit 5f28796

19 files changed

+879
-18
lines changed

docs/conf.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@
8282
assert PythonDomain.object_types["data"].roles == ("data", "obj")
8383
PythonDomain.object_types["data"].roles = ("data", "class", "obj")
8484

85-
intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
85+
intersphinx_mapping = {
86+
"python": ("https://docs.python.org/3", None),
87+
"werkzeug": ("https://werkzeug.palletsprojects.com/en/stable/", None),
88+
}
8689

8790
spelling_show_suggestions = True
8891

docs/faq/client.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ The connection is closed when exiting the context manager.
8181
How do I reconnect when the connection drops?
8282
---------------------------------------------
8383

84-
Use :func:`~websockets.asyncio.client.connect` as an asynchronous iterator::
84+
Use :func:`connect` as an asynchronous iterator::
8585

8686
from websockets.asyncio.client import connect
8787
from websockets.exceptions import ConnectionClosed

docs/faq/server.rst

+3-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ Record all connections in a global variable::
116116
finally:
117117
CONNECTIONS.remove(websocket)
118118

119-
Then, call :func:`~websockets.asyncio.server.broadcast`::
119+
Then, call :func:`broadcast`::
120120

121121
from websockets.asyncio.server import broadcast
122122

@@ -219,6 +219,8 @@ You may route a connection to different handlers depending on the request path::
219219
# No handler for this path; close the connection.
220220
return
221221

222+
For more complex routing, you may use :func:`~websockets.asyncio.router.route`.
223+
222224
You may also route the connection based on the first message received from the
223225
client, as shown in the :doc:`tutorial <../intro/tutorial2>`. When you want to
224226
authenticate the connection before routing it, this is usually more convenient.

docs/project/changelog.rst

+6
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ Backwards-incompatible changes
5656

5757
See :doc:`keepalive and latency <../topics/keepalive>` for details.
5858

59+
New features
60+
............
61+
62+
* Added :func:`~asyncio.router.route` and :func:`~asyncio.router.unix_route` to
63+
dispatch connections to different handlers depending on the URL.
64+
5965
Improvements
6066
............
6167

docs/reference/asyncio/server.rst

+17-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,21 @@ Creating a server
1212
.. autofunction:: unix_serve
1313
:async:
1414

15+
Routing connections
16+
-------------------
17+
18+
.. automodule:: websockets.asyncio.router
19+
20+
.. autofunction:: route
21+
:async:
22+
23+
.. autofunction:: unix_route
24+
:async:
25+
26+
.. autoclass:: Router
27+
28+
.. currentmodule:: websockets.asyncio.server
29+
1530
Running a server
1631
----------------
1732

@@ -89,12 +104,12 @@ Using a connection
89104
Broadcast
90105
---------
91106

92-
.. autofunction:: websockets.asyncio.server.broadcast
107+
.. autofunction:: broadcast
93108

94109
HTTP Basic Authentication
95110
-------------------------
96111

97112
websockets supports HTTP Basic Authentication according to
98113
:rfc:`7235` and :rfc:`7617`.
99114

100-
.. autofunction:: websockets.asyncio.server.basic_auth
115+
.. autofunction:: basic_auth

docs/reference/features.rst

+2
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@ Server
127127
+------------------------------------+--------+--------+--------+--------+
128128
| Perform HTTP Digest Authentication |||||
129129
+------------------------------------+--------+--------+--------+--------+
130+
| Dispatch connections to handlers |||||
131+
+------------------------------------+--------+--------+--------+--------+
130132

131133
Client
132134
------

docs/reference/sync/server.rst

+26-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,31 @@ Creating a server
1010

1111
.. autofunction:: unix_serve
1212

13+
Routing connections
14+
-------------------
15+
16+
.. automodule:: websockets.sync.router
17+
18+
.. autofunction:: route
19+
20+
.. autofunction:: unix_route
21+
22+
.. autoclass:: Router
23+
24+
.. currentmodule:: websockets.sync.server
25+
26+
Routing connections
27+
-------------------
28+
29+
.. autofunction:: route
30+
:async:
31+
32+
.. autofunction:: unix_route
33+
:async:
34+
35+
.. autoclass:: Server
36+
37+
1338
Running a server
1439
----------------
1540

@@ -78,4 +103,4 @@ HTTP Basic Authentication
78103
websockets supports HTTP Basic Authentication according to
79104
:rfc:`7235` and :rfc:`7617`.
80105

81-
.. autofunction:: websockets.sync.server.basic_auth
106+
.. autofunction:: basic_auth

docs/requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ sphinx-inline-tabs
66
sphinxcontrib-spelling
77
sphinxcontrib-trio
88
sphinxext-opengraph
9+
werkzeug

src/websockets/__init__.py

+9
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@
1212
"connect",
1313
"unix_connect",
1414
"ClientConnection",
15+
# .asyncio.router
16+
"route",
17+
"unix_route",
18+
"Router",
1519
# .asyncio.server
1620
"basic_auth",
1721
"broadcast",
@@ -79,6 +83,7 @@
7983
# When type checking, import non-deprecated aliases eagerly. Else, import on demand.
8084
if TYPE_CHECKING:
8185
from .asyncio.client import ClientConnection, connect, unix_connect
86+
from .asyncio.router import Router, route, unix_route
8287
from .asyncio.server import (
8388
Server,
8489
ServerConnection,
@@ -138,6 +143,10 @@
138143
"connect": ".asyncio.client",
139144
"unix_connect": ".asyncio.client",
140145
"ClientConnection": ".asyncio.client",
146+
# .asyncio.router
147+
"route": ".asyncio.router",
148+
"unix_route": ".asyncio.router",
149+
"Router": ".asyncio.router",
141150
# .asyncio.server
142151
"basic_auth": ".asyncio.server",
143152
"broadcast": ".asyncio.server",

src/websockets/asyncio/router.py

+196
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
from __future__ import annotations
2+
3+
import http
4+
import ssl as ssl_module
5+
import urllib.parse
6+
from typing import Any, Awaitable, Callable, Literal
7+
8+
from werkzeug.exceptions import NotFound
9+
from werkzeug.routing import Map, RequestRedirect
10+
11+
from ..http11 import Request, Response
12+
from .server import Server, ServerConnection, serve
13+
14+
15+
__all__ = ["route", "unix_route", "Router"]
16+
17+
18+
class Router:
19+
"""WebSocket router supporting :func:`route`."""
20+
21+
def __init__(
22+
self,
23+
url_map: Map,
24+
server_name: str | None = None,
25+
url_scheme: str = "ws",
26+
) -> None:
27+
self.url_map = url_map
28+
self.server_name = server_name
29+
self.url_scheme = url_scheme
30+
for rule in self.url_map.iter_rules():
31+
rule.websocket = True
32+
33+
def get_server_name(self, connection: ServerConnection, request: Request) -> str:
34+
if self.server_name is None:
35+
return request.headers["Host"]
36+
else:
37+
return self.server_name
38+
39+
def redirect(self, connection: ServerConnection, url: str) -> Response:
40+
response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}")
41+
response.headers["Location"] = url
42+
return response
43+
44+
def not_found(self, connection: ServerConnection) -> Response:
45+
return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found")
46+
47+
def route_request(
48+
self, connection: ServerConnection, request: Request
49+
) -> Response | None:
50+
"""Route incoming request."""
51+
url_map_adapter = self.url_map.bind(
52+
server_name=self.get_server_name(connection, request),
53+
url_scheme=self.url_scheme,
54+
)
55+
try:
56+
parsed = urllib.parse.urlparse(request.path)
57+
handler, kwargs = url_map_adapter.match(
58+
path_info=parsed.path,
59+
query_args=parsed.query,
60+
)
61+
except RequestRedirect as redirect:
62+
return self.redirect(connection, redirect.new_url)
63+
except NotFound:
64+
return self.not_found(connection)
65+
connection.handler, connection.handler_kwargs = handler, kwargs
66+
return None
67+
68+
async def handler(self, connection: ServerConnection) -> None:
69+
"""Handle a connection."""
70+
return await connection.handler(connection, **connection.handler_kwargs)
71+
72+
73+
def route(
74+
url_map: Map,
75+
*args: Any,
76+
server_name: str | None = None,
77+
ssl: ssl_module.SSLContext | Literal[True] | None = None,
78+
create_router: type[Router] | None = None,
79+
**kwargs: Any,
80+
) -> Awaitable[Server]:
81+
"""
82+
Create a WebSocket server dispatching connections to different handlers.
83+
84+
This feature requires the third-party library `werkzeug`_::
85+
86+
$ pip install werkzeug
87+
88+
.. _werkzeug: https://werkzeug.palletsprojects.com/
89+
90+
:func:`route` accepts the same arguments as
91+
:func:`~websockets.sync.server.serve`, except as described below.
92+
93+
The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns
94+
to connection handlers. In addition to the connection, handlers receive
95+
parameters captured in the URL as keyword arguments.
96+
97+
Here's an example::
98+
99+
100+
from websockets.asyncio.router import route
101+
from werkzeug.routing import Map, Rule
102+
103+
async def channel_handler(websocket, channel_id):
104+
...
105+
106+
url_map = Map([
107+
Rule("/channel/<uuid:channel_id>", endpoint=channel_handler),
108+
...
109+
])
110+
111+
# set this future to exit the server
112+
stop = asyncio.get_running_loop().create_future()
113+
114+
async with route(url_map, ...) as server:
115+
await stop
116+
117+
118+
Refer to the documentation of :mod:`werkzeug.routing` for details.
119+
120+
If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map,
121+
when the server runs behind a reverse proxy that modifies the ``Host``
122+
header or terminates TLS, you need additional configuration:
123+
124+
* Set ``server_name`` to the name of the server as seen by clients. When not
125+
provided, websockets uses the value of the ``Host`` header.
126+
127+
* Set ``ssl=True`` to generate ``wss://`` URIs without actually enabling
128+
TLS. Under the hood, this bind the URL map with a ``url_scheme`` of
129+
``wss://`` instead of ``ws://``.
130+
131+
There is no need to specify ``websocket=True`` in each rule. It is added
132+
automatically.
133+
134+
Args:
135+
url_map: Mapping of URL patterns to connection handlers.
136+
server_name: Name of the server as seen by clients. If :obj:`None`,
137+
websockets uses the value of the ``Host`` header.
138+
ssl: Configuration for enabling TLS on the connection. Set it to
139+
:obj:`True` if a reverse proxy terminates TLS connections.
140+
create_router: Factory for the :class:`Router` dispatching requests to
141+
handlers. Set it to a wrapper or a subclass to customize routing.
142+
143+
"""
144+
url_scheme = "ws" if ssl is None else "wss"
145+
if ssl is not True and ssl is not None:
146+
kwargs["ssl"] = ssl
147+
148+
if create_router is None:
149+
create_router = Router
150+
151+
router = create_router(url_map, server_name, url_scheme)
152+
153+
_process_request: (
154+
Callable[
155+
[ServerConnection, Request],
156+
Awaitable[Response | None] | Response | None,
157+
]
158+
| None
159+
) = kwargs.pop("process_request", None)
160+
if _process_request is None:
161+
process_request: Callable[
162+
[ServerConnection, Request],
163+
Awaitable[Response | None] | Response | None,
164+
] = router.route_request
165+
else:
166+
167+
async def process_request(
168+
connection: ServerConnection, request: Request
169+
) -> Response | None:
170+
response = _process_request(connection, request)
171+
if isinstance(response, Awaitable):
172+
response = await response
173+
if response is not None:
174+
return response
175+
return router.route_request(connection, request)
176+
177+
return serve(router.handler, *args, process_request=process_request, **kwargs)
178+
179+
180+
def unix_route(
181+
url_map: Map,
182+
path: str | None = None,
183+
**kwargs: Any,
184+
) -> Awaitable[Server]:
185+
"""
186+
Create a WebSocket Unix server dispatching connections to different handlers.
187+
188+
:func:`unix_route` combines the behaviors of :func:`route` and
189+
:func:`~websockets.asyncio.server.unix_serve`.
190+
191+
Args:
192+
url_map: Mapping of URL patterns to connection handlers.
193+
path: File system path to the Unix socket.
194+
195+
"""
196+
return route(url_map, unix=True, path=path, **kwargs)

src/websockets/asyncio/server.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import sys
1010
from collections.abc import Awaitable, Generator, Iterable, Sequence
1111
from types import TracebackType
12-
from typing import Any, Callable, cast
12+
from typing import Any, Callable, Mapping, cast
1313

1414
from ..exceptions import InvalidHeader
1515
from ..extensions.base import ServerExtensionFactory
@@ -87,6 +87,8 @@ def __init__(
8787
self.server = server
8888
self.request_rcvd: asyncio.Future[None] = self.loop.create_future()
8989
self.username: str # see basic_auth()
90+
self.handler: Callable[[ServerConnection], Awaitable[None]] # see route()
91+
self.handler_kwargs: Mapping[str, Any] # see route()
9092

9193
def respond(self, status: StatusLike, text: str) -> Response:
9294
"""

0 commit comments

Comments
 (0)