exceptions.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. from __future__ import annotations
  2. import difflib
  3. import typing as t
  4. from ..exceptions import BadRequest
  5. from ..exceptions import HTTPException
  6. from ..utils import cached_property
  7. from ..utils import redirect
  8. if t.TYPE_CHECKING:
  9. from _typeshed.wsgi import WSGIEnvironment
  10. from .map import MapAdapter
  11. from .rules import Rule
  12. from ..wrappers.request import Request
  13. from ..wrappers.response import Response
  14. class RoutingException(Exception):
  15. """Special exceptions that require the application to redirect, notifying
  16. about missing urls, etc.
  17. :internal:
  18. """
  19. class RequestRedirect(HTTPException, RoutingException):
  20. """Raise if the map requests a redirect. This is for example the case if
  21. `strict_slashes` are activated and an url that requires a trailing slash.
  22. The attribute `new_url` contains the absolute destination url.
  23. """
  24. code = 308
  25. def __init__(self, new_url: str) -> None:
  26. super().__init__(new_url)
  27. self.new_url = new_url
  28. def get_response(
  29. self,
  30. environ: WSGIEnvironment | Request | None = None,
  31. scope: dict | None = None,
  32. ) -> Response:
  33. return redirect(self.new_url, self.code)
  34. class RequestPath(RoutingException):
  35. """Internal exception."""
  36. __slots__ = ("path_info",)
  37. def __init__(self, path_info: str) -> None:
  38. super().__init__()
  39. self.path_info = path_info
  40. class RequestAliasRedirect(RoutingException): # noqa: B903
  41. """This rule is an alias and wants to redirect to the canonical URL."""
  42. def __init__(self, matched_values: t.Mapping[str, t.Any], endpoint: str) -> None:
  43. super().__init__()
  44. self.matched_values = matched_values
  45. self.endpoint = endpoint
  46. class BuildError(RoutingException, LookupError):
  47. """Raised if the build system cannot find a URL for an endpoint with the
  48. values provided.
  49. """
  50. def __init__(
  51. self,
  52. endpoint: str,
  53. values: t.Mapping[str, t.Any],
  54. method: str | None,
  55. adapter: MapAdapter | None = None,
  56. ) -> None:
  57. super().__init__(endpoint, values, method)
  58. self.endpoint = endpoint
  59. self.values = values
  60. self.method = method
  61. self.adapter = adapter
  62. @cached_property
  63. def suggested(self) -> Rule | None:
  64. return self.closest_rule(self.adapter)
  65. def closest_rule(self, adapter: MapAdapter | None) -> Rule | None:
  66. def _score_rule(rule: Rule) -> float:
  67. return sum(
  68. [
  69. 0.98
  70. * difflib.SequenceMatcher(
  71. None, rule.endpoint, self.endpoint
  72. ).ratio(),
  73. 0.01 * bool(set(self.values or ()).issubset(rule.arguments)),
  74. 0.01 * bool(rule.methods and self.method in rule.methods),
  75. ]
  76. )
  77. if adapter and adapter.map._rules:
  78. return max(adapter.map._rules, key=_score_rule)
  79. return None
  80. def __str__(self) -> str:
  81. message = [f"Could not build url for endpoint {self.endpoint!r}"]
  82. if self.method:
  83. message.append(f" ({self.method!r})")
  84. if self.values:
  85. message.append(f" with values {sorted(self.values)!r}")
  86. message.append(".")
  87. if self.suggested:
  88. if self.endpoint == self.suggested.endpoint:
  89. if (
  90. self.method
  91. and self.suggested.methods is not None
  92. and self.method not in self.suggested.methods
  93. ):
  94. message.append(
  95. " Did you mean to use methods"
  96. f" {sorted(self.suggested.methods)!r}?"
  97. )
  98. missing_values = self.suggested.arguments.union(
  99. set(self.suggested.defaults or ())
  100. ) - set(self.values.keys())
  101. if missing_values:
  102. message.append(
  103. f" Did you forget to specify values {sorted(missing_values)!r}?"
  104. )
  105. else:
  106. message.append(f" Did you mean {self.suggested.endpoint!r} instead?")
  107. return "".join(message)
  108. class WebsocketMismatch(BadRequest):
  109. """The only matched rule is either a WebSocket and the request is
  110. HTTP, or the rule is HTTP and the request is a WebSocket.
  111. """
  112. class NoMatch(Exception):
  113. __slots__ = ("have_match_for", "websocket_mismatch")
  114. def __init__(self, have_match_for: set[str], websocket_mismatch: bool) -> None:
  115. self.have_match_for = have_match_for
  116. self.websocket_mismatch = websocket_mismatch