routing.py 34 KB

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