You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

877 lines
33 KiB

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