router.py 7.0 KB

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