routing.py 32 KB

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