|
| 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 with several handlers. |
| 83 | +
|
| 84 | + Except for the differences described below, this function accepts the same |
| 85 | + arguments as :func:`~websockets.sync.server.serve`. |
| 86 | +
|
| 87 | + The first argument is a :class:`werkzeug.routing.Map` mapping URL patterns |
| 88 | + to connection handlers, instead of a single connection handler:: |
| 89 | +
|
| 90 | + from websockets.sync.router import route |
| 91 | + from werkzeug.routing import Map, Rule |
| 92 | +
|
| 93 | + url_map = Map([ |
| 94 | + Rule("/", endpoint=default_handler), |
| 95 | + ... |
| 96 | + ]) |
| 97 | +
|
| 98 | + with router(url_map, ...) as server: |
| 99 | + server.serve_forever() |
| 100 | +
|
| 101 | + Handlers are called with the connection and any keyword arguments captured |
| 102 | + in the URL. |
| 103 | +
|
| 104 | + There is no need to specify ``websocket=True`` in ``url_map``. It is added |
| 105 | + to each rule automatically. |
| 106 | +
|
| 107 | + This feature requires the third-party library `werkzeug`_:: |
| 108 | +
|
| 109 | + $ pip install werkzeug |
| 110 | +
|
| 111 | + .. _werkzeug: https://werkzeug.palletsprojects.com/ |
| 112 | +
|
| 113 | + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map |
| 114 | + and the server runs behind a reverse proxy that modifies the ``Host`` header |
| 115 | + or terminates TLS, you need the following configuration: |
| 116 | +
|
| 117 | + * Set ``server_name`` to the name of the server as seen by clients. When |
| 118 | + not provided, websockets uses the value of the ``Host`` header. |
| 119 | +
|
| 120 | + * Set ``ssl=True`` to generate ``wss://`` URIs without actually enabling |
| 121 | + TLS. Under the hood, this bind the URL map with a ``url_scheme`` of |
| 122 | + ``wss://`` instead of ``ws://``. |
| 123 | +
|
| 124 | + Args: |
| 125 | + url_map: Mapping of URL patterns to connection handlers. |
| 126 | + server_name: Name of the server as seen by clients. If :obj:`None`, |
| 127 | + websockets uses the value of the ``Host`` header. |
| 128 | + ssl: Configuration for enabling TLS on the connection. Set it to |
| 129 | + :obj:`True` if a reverse proxy terminates TLS connections. |
| 130 | + create_router: Factory for the :class:`Router` dispatching requests to |
| 131 | + handlers. Set it to a wrapper or a subclass to customize routing. |
| 132 | +
|
| 133 | + """ |
| 134 | + url_scheme = "ws" if ssl is None else "wss" |
| 135 | + if ssl is not True and ssl is not None: |
| 136 | + kwargs["ssl"] = ssl |
| 137 | + |
| 138 | + if create_router is None: |
| 139 | + create_router = Router |
| 140 | + |
| 141 | + router = create_router(url_map, server_name, url_scheme) |
| 142 | + |
| 143 | + _process_request: ( |
| 144 | + Callable[ |
| 145 | + [ServerConnection, Request], |
| 146 | + Awaitable[Response | None] | Response | None, |
| 147 | + ] |
| 148 | + | None |
| 149 | + ) = kwargs.pop("process_request", None) |
| 150 | + if _process_request is None: |
| 151 | + process_request: Callable[ |
| 152 | + [ServerConnection, Request], |
| 153 | + Awaitable[Response | None] | Response | None, |
| 154 | + ] = router.route_request |
| 155 | + else: |
| 156 | + |
| 157 | + async def process_request( |
| 158 | + connection: ServerConnection, request: Request |
| 159 | + ) -> Response | None: |
| 160 | + response = _process_request(connection, request) |
| 161 | + if isinstance(response, Awaitable): |
| 162 | + response = await response |
| 163 | + if response is not None: |
| 164 | + return response |
| 165 | + return router.route_request(connection, request) |
| 166 | + |
| 167 | + return serve(router.handler, *args, process_request=process_request, **kwargs) |
| 168 | + |
| 169 | + |
| 170 | +def unix_route( |
| 171 | + url_map: Map, |
| 172 | + path: str | None = None, |
| 173 | + **kwargs: Any, |
| 174 | +) -> Awaitable[Server]: |
| 175 | + """ |
| 176 | + Create a WebSocket Unix server with several handlers. |
| 177 | +
|
| 178 | + This function combines behaviors of :func:`~websockets.sync.router.route` |
| 179 | + and :func:`~websockets.sync.server.unix_serve`. |
| 180 | +
|
| 181 | + Args: |
| 182 | + url_map: Mapping of URL patterns to connection handlers. |
| 183 | + path: File system path to the Unix socket. |
| 184 | +
|
| 185 | + """ |
| 186 | + return route(url_map, unix=True, path=path, **kwargs) |
0 commit comments