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