router.py 7.3 KB

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