|
| 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) |
0 commit comments