Skip to content

Commit 51eadfe

Browse files
committed
Add a router based on werkzeug.routing.
Fix #311.
1 parent 7a2f8f4 commit 51eadfe

File tree

13 files changed

+381
-6
lines changed

13 files changed

+381
-6
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/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` to dispatch connections to different
63+
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

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

1111
.. autofunction:: unix_serve
1212

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

@@ -78,4 +105,4 @@ HTTP Basic Authentication
78105
websockets supports HTTP Basic Authentication according to
79106
:rfc:`7235` and :rfc:`7617`.
80107

81-
.. autofunction:: websockets.sync.server.basic_auth
108+
.. 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

+155
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import http
2+
from typing import Any, Awaitable, Callable
3+
4+
from werkzeug.exceptions import NotFound
5+
from werkzeug.routing import Map, RequestRedirect
6+
7+
from ..http11 import Request, Response
8+
from .server import Server, ServerConnection, serve
9+
10+
11+
__all__ = ["route", "unix_route", "Router"]
12+
13+
14+
class Router:
15+
"""WebSocket router supporting :func:`route`."""
16+
17+
def __init__(self, url_map: Map, url_scheme: str = "ws") -> None:
18+
self.url_map = url_map
19+
self.url_scheme = url_scheme
20+
for rule in self.url_map.iter_rules():
21+
rule.websocket = True
22+
23+
def get_server_name(self, connection: ServerConnection, request: Request) -> str:
24+
return request.headers["Host"]
25+
26+
def redirect(self, connection: ServerConnection, url: str) -> Response:
27+
response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}")
28+
response.headers["Location"] = url
29+
return response
30+
31+
def not_found(self, connection: ServerConnection) -> Response:
32+
return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found")
33+
34+
def route_request(
35+
self, connection: ServerConnection, request: Request
36+
) -> Response | None:
37+
"""Route incoming request."""
38+
server_name = self.get_server_name(connection, request)
39+
url_map_adapter = self.url_map.bind(server_name, url_scheme=self.url_scheme)
40+
try:
41+
handler, kwargs = url_map_adapter.match(request.path)
42+
except RequestRedirect as redirect:
43+
return self.redirect(connection, redirect.new_url)
44+
except NotFound:
45+
return self.not_found(connection)
46+
connection.handler, connection.handler_kwargs = handler, kwargs
47+
return None
48+
49+
async def handler(self, connection: ServerConnection) -> None:
50+
"""Handler for the connection."""
51+
return await connection.handler(connection, **connection.handler_kwargs)
52+
53+
54+
def route(
55+
url_map: Map,
56+
*args: Any,
57+
create_router: type[Router] | None = None,
58+
**kwargs: Any,
59+
) -> Awaitable[Server]:
60+
"""
61+
Create a WebSocket server with several handlers.
62+
63+
Except for differences described below, this function accepts the same
64+
arguments as :func:`~websockets.sync.server.serve`.
65+
66+
The first argument is a :class:`werkzeug.routing.Map` mapping URL patterns
67+
to connection handlers, instead of a single connection handler::
68+
69+
from websockets.sync.router import route
70+
from werkzeug.routing import Map, Rule
71+
72+
url_map = Map([
73+
Rule("/", endpoint=default_handler),
74+
...
75+
])
76+
77+
with router(url_map, ...) as server:
78+
server.serve_forever()
79+
80+
Handlers are called with the connection and any keyword arguments captured
81+
in the URL.
82+
83+
There is no need to specify ``websocket=True`` in ``url_map``. It is added
84+
to each rule automatically.
85+
86+
This feature requires the third-party library `werkzeug`_::
87+
88+
$ pip install werkzeug
89+
90+
.. _werkzeug: https://werkzeug.palletsprojects.com/
91+
92+
If the server is behind a reverse proxy that terminates SSL, set ``ssl=True``
93+
to bind the URL map with a ``url_scheme`` of ``wss://`` instead of ``ws://``.
94+
This doesn't enable TLS on the server.
95+
96+
Args:
97+
url_map: Mapping of URL patterns to connection handlers.
98+
create_router: Factory for the :class:`Router` dispatching requests to
99+
handlers. Set it to a wrapper or a subclass to customize routing.
100+
101+
"""
102+
url_scheme = "ws"
103+
if kwargs.get("ssl", None) is True:
104+
del kwargs["ssl"]
105+
url_scheme = "wss"
106+
107+
if create_router is None:
108+
create_router = Router
109+
110+
router = create_router(url_map, url_scheme=url_scheme)
111+
112+
_process_request: (
113+
Callable[
114+
[ServerConnection, Request],
115+
Awaitable[Response | None] | Response | None,
116+
]
117+
| None
118+
) = kwargs.pop("process_request", None)
119+
if _process_request is None:
120+
process_request: Callable[
121+
[ServerConnection, Request],
122+
Awaitable[Response | None] | Response | None,
123+
] = router.route_request
124+
else:
125+
126+
async def process_request(
127+
connection: ServerConnection, request: Request
128+
) -> Response | None:
129+
response = _process_request(connection, request)
130+
if isinstance(response, Awaitable):
131+
response = await response
132+
if response is not None:
133+
return response
134+
return router.route_request(connection, request)
135+
136+
return serve(router.handler, *args, process_request=process_request, **kwargs)
137+
138+
139+
def unix_route(
140+
url_map: Map,
141+
path: str | None = None,
142+
**kwargs: Any,
143+
) -> Awaitable[Server]:
144+
"""
145+
Create a WebSocket Unix server with several handlers.
146+
147+
This function combines behaviors of :func:`~websockets.sync.router.route`
148+
and :func:`~websockets.sync.server.unix_serve`.
149+
150+
Args:
151+
url_map: Mapping of URL patterns to connection handlers.
152+
path: File system path to the Unix socket.
153+
154+
"""
155+
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)