routing.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. from __future__ import annotations
  2. import contextlib
  3. import functools
  4. import inspect
  5. import re
  6. import traceback
  7. import types
  8. import warnings
  9. from collections.abc import Awaitable, Callable, Collection, Generator, Sequence
  10. from contextlib import AbstractAsyncContextManager, AbstractContextManager, asynccontextmanager
  11. from enum import Enum
  12. from re import Pattern
  13. from typing import Any, TypeVar
  14. from starlette._exception_handler import wrap_app_handling_exceptions
  15. from starlette._utils import get_route_path, is_async_callable
  16. from starlette.concurrency import run_in_threadpool
  17. from starlette.convertors import CONVERTOR_TYPES, Convertor
  18. from starlette.datastructures import URL, Headers, URLPath
  19. from starlette.exceptions import HTTPException
  20. from starlette.middleware import Middleware
  21. from starlette.requests import Request
  22. from starlette.responses import PlainTextResponse, RedirectResponse, Response
  23. from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send
  24. from starlette.websockets import WebSocket, WebSocketClose
  25. class NoMatchFound(Exception):
  26. """
  27. Raised by `.url_for(name, **path_params)` and `.url_path_for(name, **path_params)`
  28. if no matching route exists.
  29. """
  30. def __init__(self, name: str, path_params: dict[str, Any]) -> None:
  31. params = ", ".join(list(path_params.keys()))
  32. super().__init__(f'No route exists for name "{name}" and params "{params}".')
  33. class Match(Enum):
  34. NONE = 0
  35. PARTIAL = 1
  36. FULL = 2
  37. def request_response(
  38. func: Callable[[Request], Awaitable[Response] | Response],
  39. ) -> ASGIApp:
  40. """
  41. Takes a function or coroutine `func(request) -> response`,
  42. and returns an ASGI application.
  43. """
  44. f: Callable[[Request], Awaitable[Response]] = (
  45. func if is_async_callable(func) else functools.partial(run_in_threadpool, func)
  46. )
  47. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  48. request = Request(scope, receive, send)
  49. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  50. response = await f(request)
  51. await response(scope, receive, send)
  52. await wrap_app_handling_exceptions(app, request)(scope, receive, send)
  53. return app
  54. def websocket_session(
  55. func: Callable[[WebSocket], Awaitable[None]],
  56. ) -> ASGIApp:
  57. """
  58. Takes a coroutine `func(session)`, and returns an ASGI application.
  59. """
  60. # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
  61. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  62. session = WebSocket(scope, receive=receive, send=send)
  63. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  64. await func(session)
  65. await wrap_app_handling_exceptions(app, session)(scope, receive, send)
  66. return app
  67. def get_name(endpoint: Callable[..., Any]) -> str:
  68. return getattr(endpoint, "__name__", endpoint.__class__.__name__)
  69. def replace_params(
  70. path: str,
  71. param_convertors: dict[str, Convertor[Any]],
  72. path_params: dict[str, str],
  73. ) -> tuple[str, dict[str, str]]:
  74. for key, value in list(path_params.items()):
  75. if "{" + key + "}" in path:
  76. convertor = param_convertors[key]
  77. value = convertor.to_string(value)
  78. path = path.replace("{" + key + "}", value)
  79. path_params.pop(key)
  80. return path, path_params
  81. # Match parameters in URL paths, eg. '{param}', and '{param:int}'
  82. PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
  83. def compile_path(
  84. path: str,
  85. ) -> tuple[Pattern[str], str, dict[str, Convertor[Any]]]:
  86. """
  87. Given a path string, like: "/{username:str}",
  88. or a host string, like: "{subdomain}.mydomain.org", return a three-tuple
  89. of (regex, format, {param_name:convertor}).
  90. regex: "/(?P<username>[^/]+)"
  91. format: "/{username}"
  92. convertors: {"username": StringConvertor()}
  93. """
  94. is_host = not path.startswith("/")
  95. path_regex = "^"
  96. path_format = ""
  97. duplicated_params: set[str] = set()
  98. idx = 0
  99. param_convertors = {}
  100. for match in PARAM_REGEX.finditer(path):
  101. param_name, convertor_type = match.groups("str")
  102. convertor_type = convertor_type.lstrip(":")
  103. assert convertor_type in CONVERTOR_TYPES, f"Unknown path convertor '{convertor_type}'"
  104. convertor = CONVERTOR_TYPES[convertor_type]
  105. path_regex += re.escape(path[idx : match.start()])
  106. path_regex += f"(?P<{param_name}>{convertor.regex})"
  107. path_format += path[idx : match.start()]
  108. path_format += "{%s}" % param_name
  109. if param_name in param_convertors:
  110. duplicated_params.add(param_name)
  111. param_convertors[param_name] = convertor
  112. idx = match.end()
  113. if duplicated_params:
  114. names = ", ".join(sorted(duplicated_params))
  115. ending = "s" if len(duplicated_params) > 1 else ""
  116. raise ValueError(f"Duplicated param name{ending} {names} at path {path}")
  117. if is_host:
  118. # Align with `Host.matches()` behavior, which ignores port.
  119. hostname = path[idx:].split(":")[0]
  120. path_regex += re.escape(hostname) + "$"
  121. else:
  122. path_regex += re.escape(path[idx:]) + "$"
  123. path_format += path[idx:]
  124. return re.compile(path_regex), path_format, param_convertors
  125. class BaseRoute:
  126. def matches(self, scope: Scope) -> tuple[Match, Scope]:
  127. raise NotImplementedError() # pragma: no cover
  128. def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
  129. raise NotImplementedError() # pragma: no cover
  130. async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
  131. raise NotImplementedError() # pragma: no cover
  132. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  133. """
  134. A route may be used in isolation as a stand-alone ASGI app.
  135. This is a somewhat contrived case, as they'll almost always be used
  136. within a Router, but could be useful for some tooling and minimal apps.
  137. """
  138. match, child_scope = self.matches(scope)
  139. if match == Match.NONE:
  140. if scope["type"] == "http":
  141. response = PlainTextResponse("Not Found", status_code=404)
  142. await response(scope, receive, send)
  143. elif scope["type"] == "websocket": # pragma: no branch
  144. websocket_close = WebSocketClose()
  145. await websocket_close(scope, receive, send)
  146. return
  147. scope.update(child_scope)
  148. await self.handle(scope, receive, send)
  149. class Route(BaseRoute):
  150. def __init__(
  151. self,
  152. path: str,
  153. endpoint: Callable[..., Any],
  154. *,
  155. methods: Collection[str] | None = None,
  156. name: str | None = None,
  157. include_in_schema: bool = True,
  158. middleware: Sequence[Middleware] | None = None,
  159. ) -> None:
  160. assert path.startswith("/"), "Routed paths must start with '/'"
  161. self.path = path
  162. self.endpoint = endpoint
  163. self.name = get_name(endpoint) if name is None else name
  164. self.include_in_schema = include_in_schema
  165. endpoint_handler = endpoint
  166. while isinstance(endpoint_handler, functools.partial):
  167. endpoint_handler = endpoint_handler.func
  168. if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler):
  169. # Endpoint is function or method. Treat it as `func(request) -> response`.
  170. self.app = request_response(endpoint)
  171. if methods is None:
  172. methods = ["GET"]
  173. else:
  174. # Endpoint is a class. Treat it as ASGI.
  175. self.app = endpoint
  176. if middleware is not None:
  177. for cls, args, kwargs in reversed(middleware):
  178. self.app = cls(self.app, *args, **kwargs)
  179. if methods is None:
  180. self.methods = None
  181. else:
  182. self.methods = {method.upper() for method in methods}
  183. if "GET" in self.methods:
  184. self.methods.add("HEAD")
  185. self.path_regex, self.path_format, self.param_convertors = compile_path(path)
  186. def matches(self, scope: Scope) -> tuple[Match, Scope]:
  187. path_params: dict[str, Any]
  188. if scope["type"] == "http":
  189. route_path = get_route_path(scope)
  190. match = self.path_regex.match(route_path)
  191. if match:
  192. matched_params = match.groupdict()
  193. for key, value in matched_params.items():
  194. matched_params[key] = self.param_convertors[key].convert(value)
  195. path_params = dict(scope.get("path_params", {}))
  196. path_params.update(matched_params)
  197. child_scope = {"endpoint": self.endpoint, "path_params": path_params}
  198. if self.methods and scope["method"] not in self.methods:
  199. return Match.PARTIAL, child_scope
  200. else:
  201. return Match.FULL, child_scope
  202. return Match.NONE, {}
  203. def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
  204. seen_params = set(path_params.keys())
  205. expected_params = set(self.param_convertors.keys())
  206. if name != self.name or seen_params != expected_params:
  207. raise NoMatchFound(name, path_params)
  208. path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
  209. assert not remaining_params
  210. return URLPath(path=path, protocol="http")
  211. async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
  212. if self.methods and scope["method"] not in self.methods:
  213. headers = {"Allow": ", ".join(self.methods)}
  214. if "app" in scope:
  215. raise HTTPException(status_code=405, headers=headers)
  216. else:
  217. response = PlainTextResponse("Method Not Allowed", status_code=405, headers=headers)
  218. await response(scope, receive, send)
  219. else:
  220. await self.app(scope, receive, send)
  221. def __eq__(self, other: Any) -> bool:
  222. return (
  223. isinstance(other, Route)
  224. and self.path == other.path
  225. and self.endpoint == other.endpoint
  226. and self.methods == other.methods
  227. )
  228. def __repr__(self) -> str:
  229. class_name = self.__class__.__name__
  230. methods = sorted(self.methods or [])
  231. path, name = self.path, self.name
  232. return f"{class_name}(path={path!r}, name={name!r}, methods={methods!r})"
  233. class WebSocketRoute(BaseRoute):
  234. def __init__(
  235. self,
  236. path: str,
  237. endpoint: Callable[..., Any],
  238. *,
  239. name: str | None = None,
  240. middleware: Sequence[Middleware] | None = None,
  241. ) -> None:
  242. assert path.startswith("/"), "Routed paths must start with '/'"
  243. self.path = path
  244. self.endpoint = endpoint
  245. self.name = get_name(endpoint) if name is None else name
  246. endpoint_handler = endpoint
  247. while isinstance(endpoint_handler, functools.partial):
  248. endpoint_handler = endpoint_handler.func
  249. if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler):
  250. # Endpoint is function or method. Treat it as `func(websocket)`.
  251. self.app = websocket_session(endpoint)
  252. else:
  253. # Endpoint is a class. Treat it as ASGI.
  254. self.app = endpoint
  255. if middleware is not None:
  256. for cls, args, kwargs in reversed(middleware):
  257. self.app = cls(self.app, *args, **kwargs)
  258. self.path_regex, self.path_format, self.param_convertors = compile_path(path)
  259. def matches(self, scope: Scope) -> tuple[Match, Scope]:
  260. path_params: dict[str, Any]
  261. if scope["type"] == "websocket":
  262. route_path = get_route_path(scope)
  263. match = self.path_regex.match(route_path)
  264. if match:
  265. matched_params = match.groupdict()
  266. for key, value in matched_params.items():
  267. matched_params[key] = self.param_convertors[key].convert(value)
  268. path_params = dict(scope.get("path_params", {}))
  269. path_params.update(matched_params)
  270. child_scope = {"endpoint": self.endpoint, "path_params": path_params}
  271. return Match.FULL, child_scope
  272. return Match.NONE, {}
  273. def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
  274. seen_params = set(path_params.keys())
  275. expected_params = set(self.param_convertors.keys())
  276. if name != self.name or seen_params != expected_params:
  277. raise NoMatchFound(name, path_params)
  278. path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
  279. assert not remaining_params
  280. return URLPath(path=path, protocol="websocket")
  281. async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
  282. await self.app(scope, receive, send)
  283. def __eq__(self, other: Any) -> bool:
  284. return isinstance(other, WebSocketRoute) and self.path == other.path and self.endpoint == other.endpoint
  285. def __repr__(self) -> str:
  286. return f"{self.__class__.__name__}(path={self.path!r}, name={self.name!r})"
  287. class Mount(BaseRoute):
  288. def __init__(
  289. self,
  290. path: str,
  291. app: ASGIApp | None = None,
  292. routes: Sequence[BaseRoute] | None = None,
  293. name: str | None = None,
  294. *,
  295. middleware: Sequence[Middleware] | None = None,
  296. ) -> None:
  297. assert path == "" or path.startswith("/"), "Routed paths must start with '/'"
  298. assert app is not None or routes is not None, "Either 'app=...', or 'routes=' must be specified"
  299. self.path = path.rstrip("/")
  300. if app is not None:
  301. self._base_app: ASGIApp = app
  302. else:
  303. self._base_app = Router(routes=routes)
  304. self.app = self._base_app
  305. if middleware is not None:
  306. for cls, args, kwargs in reversed(middleware):
  307. self.app = cls(self.app, *args, **kwargs)
  308. self.name = name
  309. self.path_regex, self.path_format, self.param_convertors = compile_path(self.path + "/{path:path}")
  310. @property
  311. def routes(self) -> list[BaseRoute]:
  312. return getattr(self._base_app, "routes", [])
  313. def matches(self, scope: Scope) -> tuple[Match, Scope]:
  314. path_params: dict[str, Any]
  315. if scope["type"] in ("http", "websocket"): # pragma: no branch
  316. root_path = scope.get("root_path", "")
  317. route_path = get_route_path(scope)
  318. match = self.path_regex.match(route_path)
  319. if match:
  320. matched_params = match.groupdict()
  321. for key, value in matched_params.items():
  322. matched_params[key] = self.param_convertors[key].convert(value)
  323. remaining_path = "/" + matched_params.pop("path")
  324. matched_path = route_path[: -len(remaining_path)]
  325. path_params = dict(scope.get("path_params", {}))
  326. path_params.update(matched_params)
  327. child_scope = {
  328. "path_params": path_params,
  329. # app_root_path will only be set at the top level scope,
  330. # initialized with the (optional) value of a root_path
  331. # set above/before Starlette. And even though any
  332. # mount will have its own child scope with its own respective
  333. # root_path, the app_root_path will always be available in all
  334. # the child scopes with the same top level value because it's
  335. # set only once here with a default, any other child scope will
  336. # just inherit that app_root_path default value stored in the
  337. # scope. All this is needed to support Request.url_for(), as it
  338. # uses the app_root_path to build the URL path.
  339. "app_root_path": scope.get("app_root_path", root_path),
  340. "root_path": root_path + matched_path,
  341. "endpoint": self.app,
  342. }
  343. return Match.FULL, child_scope
  344. return Match.NONE, {}
  345. def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
  346. if self.name is not None and name == self.name and "path" in path_params:
  347. # 'name' matches "<mount_name>".
  348. path_params["path"] = path_params["path"].lstrip("/")
  349. path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
  350. if not remaining_params:
  351. return URLPath(path=path)
  352. elif self.name is None or name.startswith(self.name + ":"):
  353. if self.name is None:
  354. # No mount name.
  355. remaining_name = name
  356. else:
  357. # 'name' matches "<mount_name>:<child_name>".
  358. remaining_name = name[len(self.name) + 1 :]
  359. path_kwarg = path_params.get("path")
  360. path_params["path"] = ""
  361. path_prefix, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
  362. if path_kwarg is not None:
  363. remaining_params["path"] = path_kwarg
  364. for route in self.routes or []:
  365. try:
  366. url = route.url_path_for(remaining_name, **remaining_params)
  367. return URLPath(path=path_prefix.rstrip("/") + str(url), protocol=url.protocol)
  368. except NoMatchFound:
  369. pass
  370. raise NoMatchFound(name, path_params)
  371. async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
  372. await self.app(scope, receive, send)
  373. def __eq__(self, other: Any) -> bool:
  374. return isinstance(other, Mount) and self.path == other.path and self.app == other.app
  375. def __repr__(self) -> str:
  376. class_name = self.__class__.__name__
  377. name = self.name or ""
  378. return f"{class_name}(path={self.path!r}, name={name!r}, app={self.app!r})"
  379. class Host(BaseRoute):
  380. def __init__(self, host: str, app: ASGIApp, name: str | None = None) -> None:
  381. assert not host.startswith("/"), "Host must not start with '/'"
  382. self.host = host
  383. self.app = app
  384. self.name = name
  385. self.host_regex, self.host_format, self.param_convertors = compile_path(host)
  386. @property
  387. def routes(self) -> list[BaseRoute]:
  388. return getattr(self.app, "routes", [])
  389. def matches(self, scope: Scope) -> tuple[Match, Scope]:
  390. if scope["type"] in ("http", "websocket"): # pragma:no branch
  391. headers = Headers(scope=scope)
  392. host = headers.get("host", "").split(":")[0]
  393. match = self.host_regex.match(host)
  394. if match:
  395. matched_params = match.groupdict()
  396. for key, value in matched_params.items():
  397. matched_params[key] = self.param_convertors[key].convert(value)
  398. path_params = dict(scope.get("path_params", {}))
  399. path_params.update(matched_params)
  400. child_scope = {"path_params": path_params, "endpoint": self.app}
  401. return Match.FULL, child_scope
  402. return Match.NONE, {}
  403. def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
  404. if self.name is not None and name == self.name and "path" in path_params:
  405. # 'name' matches "<mount_name>".
  406. path = path_params.pop("path")
  407. host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params)
  408. if not remaining_params:
  409. return URLPath(path=path, host=host)
  410. elif self.name is None or name.startswith(self.name + ":"):
  411. if self.name is None:
  412. # No mount name.
  413. remaining_name = name
  414. else:
  415. # 'name' matches "<mount_name>:<child_name>".
  416. remaining_name = name[len(self.name) + 1 :]
  417. host, remaining_params = replace_params(self.host_format, self.param_convertors, path_params)
  418. for route in self.routes or []:
  419. try:
  420. url = route.url_path_for(remaining_name, **remaining_params)
  421. return URLPath(path=str(url), protocol=url.protocol, host=host)
  422. except NoMatchFound:
  423. pass
  424. raise NoMatchFound(name, path_params)
  425. async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
  426. await self.app(scope, receive, send)
  427. def __eq__(self, other: Any) -> bool:
  428. return isinstance(other, Host) and self.host == other.host and self.app == other.app
  429. def __repr__(self) -> str:
  430. class_name = self.__class__.__name__
  431. name = self.name or ""
  432. return f"{class_name}(host={self.host!r}, name={name!r}, app={self.app!r})"
  433. _T = TypeVar("_T")
  434. class _AsyncLiftContextManager(AbstractAsyncContextManager[_T]):
  435. def __init__(self, cm: AbstractContextManager[_T]):
  436. self._cm = cm
  437. async def __aenter__(self) -> _T:
  438. return self._cm.__enter__()
  439. async def __aexit__(
  440. self,
  441. exc_type: type[BaseException] | None,
  442. exc_value: BaseException | None,
  443. traceback: types.TracebackType | None,
  444. ) -> bool | None:
  445. return self._cm.__exit__(exc_type, exc_value, traceback)
  446. def _wrap_gen_lifespan_context(
  447. lifespan_context: Callable[[Any], Generator[Any, Any, Any]],
  448. ) -> Callable[[Any], AbstractAsyncContextManager[Any]]:
  449. cmgr = contextlib.contextmanager(lifespan_context)
  450. @functools.wraps(cmgr)
  451. def wrapper(app: Any) -> _AsyncLiftContextManager[Any]:
  452. return _AsyncLiftContextManager(cmgr(app))
  453. return wrapper
  454. class _DefaultLifespan:
  455. def __init__(self, router: Router):
  456. self._router = router
  457. async def __aenter__(self) -> None:
  458. pass
  459. async def __aexit__(self, *exc_info: object) -> None:
  460. pass
  461. def __call__(self: _T, app: object) -> _T:
  462. return self
  463. class Router:
  464. def __init__(
  465. self,
  466. routes: Sequence[BaseRoute] | None = None,
  467. redirect_slashes: bool = True,
  468. default: ASGIApp | None = None,
  469. # the generic to Lifespan[AppType] is the type of the top level application
  470. # which the router cannot know statically, so we use Any
  471. lifespan: Lifespan[Any] | None = None,
  472. *,
  473. middleware: Sequence[Middleware] | None = None,
  474. ) -> None:
  475. self.routes = [] if routes is None else list(routes)
  476. self.redirect_slashes = redirect_slashes
  477. self.default = self.not_found if default is None else default
  478. if lifespan is None:
  479. self.lifespan_context: Lifespan[Any] = _DefaultLifespan(self)
  480. elif inspect.isasyncgenfunction(lifespan):
  481. warnings.warn(
  482. "async generator function lifespans are deprecated, "
  483. "use an @contextlib.asynccontextmanager function instead",
  484. DeprecationWarning,
  485. )
  486. self.lifespan_context = asynccontextmanager(lifespan)
  487. elif inspect.isgeneratorfunction(lifespan):
  488. warnings.warn(
  489. "generator function lifespans are deprecated, use an @contextlib.asynccontextmanager function instead",
  490. DeprecationWarning,
  491. )
  492. self.lifespan_context = _wrap_gen_lifespan_context(lifespan)
  493. else:
  494. self.lifespan_context = lifespan
  495. self.middleware_stack = self.app
  496. if middleware:
  497. for cls, args, kwargs in reversed(middleware):
  498. self.middleware_stack = cls(self.middleware_stack, *args, **kwargs)
  499. async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:
  500. if scope["type"] == "websocket":
  501. websocket_close = WebSocketClose()
  502. await websocket_close(scope, receive, send)
  503. return
  504. # If we're running inside a starlette application then raise an
  505. # exception, so that the configurable exception handler can deal with
  506. # returning the response. For plain ASGI apps, just return the response.
  507. if "app" in scope:
  508. raise HTTPException(status_code=404)
  509. else:
  510. response = PlainTextResponse("Not Found", status_code=404)
  511. await response(scope, receive, send)
  512. def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
  513. for route in self.routes:
  514. try:
  515. return route.url_path_for(name, **path_params)
  516. except NoMatchFound:
  517. pass
  518. raise NoMatchFound(name, path_params)
  519. async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:
  520. """
  521. Handle ASGI lifespan messages, which allows us to manage application
  522. startup and shutdown events.
  523. """
  524. started = False
  525. app: Any = scope.get("app")
  526. await receive()
  527. try:
  528. async with self.lifespan_context(app) as maybe_state:
  529. if maybe_state is not None:
  530. if "state" not in scope:
  531. raise RuntimeError('The server does not support "state" in the lifespan scope.')
  532. scope["state"].update(maybe_state)
  533. await send({"type": "lifespan.startup.complete"})
  534. started = True
  535. await receive()
  536. except BaseException:
  537. exc_text = traceback.format_exc()
  538. if started:
  539. await send({"type": "lifespan.shutdown.failed", "message": exc_text})
  540. else:
  541. await send({"type": "lifespan.startup.failed", "message": exc_text})
  542. raise
  543. else:
  544. await send({"type": "lifespan.shutdown.complete"})
  545. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  546. """
  547. The main entry point to the Router class.
  548. """
  549. await self.middleware_stack(scope, receive, send)
  550. async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
  551. assert scope["type"] in ("http", "websocket", "lifespan")
  552. if "router" not in scope:
  553. scope["router"] = self
  554. if scope["type"] == "lifespan":
  555. await self.lifespan(scope, receive, send)
  556. return
  557. partial = None
  558. for route in self.routes:
  559. # Determine if any route matches the incoming scope,
  560. # and hand over to the matching route if found.
  561. match, child_scope = route.matches(scope)
  562. if match == Match.FULL:
  563. scope.update(child_scope)
  564. await route.handle(scope, receive, send)
  565. return
  566. elif match == Match.PARTIAL and partial is None:
  567. partial = route
  568. partial_scope = child_scope
  569. if partial is not None:
  570. #  Handle partial matches. These are cases where an endpoint is
  571. # able to handle the request, but is not a preferred option.
  572. # We use this in particular to deal with "405 Method Not Allowed".
  573. scope.update(partial_scope)
  574. await partial.handle(scope, receive, send)
  575. return
  576. route_path = get_route_path(scope)
  577. if scope["type"] == "http" and self.redirect_slashes and route_path != "/":
  578. redirect_scope = dict(scope)
  579. if route_path.endswith("/"):
  580. redirect_scope["path"] = redirect_scope["path"].rstrip("/")
  581. else:
  582. redirect_scope["path"] = redirect_scope["path"] + "/"
  583. for route in self.routes:
  584. match, child_scope = route.matches(redirect_scope)
  585. if match != Match.NONE:
  586. redirect_url = URL(scope=redirect_scope)
  587. response = RedirectResponse(url=str(redirect_url))
  588. await response(scope, receive, send)
  589. return
  590. await self.default(scope, receive, send)
  591. def __eq__(self, other: Any) -> bool:
  592. return isinstance(other, Router) and self.routes == other.routes
  593. def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None: # pragma: no cover
  594. route = Mount(path, app=app, name=name)
  595. self.routes.append(route)
  596. def host(self, host: str, app: ASGIApp, name: str | None = None) -> None: # pragma: no cover
  597. route = Host(host, app=app, name=name)
  598. self.routes.append(route)
  599. def add_route(
  600. self,
  601. path: str,
  602. endpoint: Callable[[Request], Awaitable[Response] | Response],
  603. methods: Collection[str] | None = None,
  604. name: str | None = None,
  605. include_in_schema: bool = True,
  606. ) -> None: # pragma: no cover
  607. route = Route(
  608. path,
  609. endpoint=endpoint,
  610. methods=methods,
  611. name=name,
  612. include_in_schema=include_in_schema,
  613. )
  614. self.routes.append(route)
  615. def add_websocket_route(
  616. self,
  617. path: str,
  618. endpoint: Callable[[WebSocket], Awaitable[None]],
  619. name: str | None = None,
  620. ) -> None: # pragma: no cover
  621. route = WebSocketRoute(path, endpoint=endpoint, name=name)
  622. self.routes.append(route)