exceptions.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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 ..wrappers.request import Request
  11. from ..wrappers.response import Response
  12. from .map import MapAdapter
  13. from .rules import Rule
  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[str, t.Any] | 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: t.Any) -> 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: t.Any,
  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. # endpoints can be any type, compare as strings
  72. None,
  73. str(rule.endpoint),
  74. str(self.endpoint),
  75. ).ratio(),
  76. 0.01 * bool(set(self.values or ()).issubset(rule.arguments)),
  77. 0.01 * bool(rule.methods and self.method in rule.methods),
  78. ]
  79. )
  80. if adapter and adapter.map._rules:
  81. return max(adapter.map._rules, key=_score_rule)
  82. return None
  83. def __str__(self) -> str:
  84. message = [f"Could not build url for endpoint {self.endpoint!r}"]
  85. if self.method:
  86. message.append(f" ({self.method!r})")
  87. if self.values:
  88. message.append(f" with values {sorted(self.values)!r}")
  89. message.append(".")
  90. if self.suggested:
  91. if self.endpoint == self.suggested.endpoint:
  92. if (
  93. self.method
  94. and self.suggested.methods is not None
  95. and self.method not in self.suggested.methods
  96. ):
  97. message.append(
  98. " Did you mean to use methods"
  99. f" {sorted(self.suggested.methods)!r}?"
  100. )
  101. missing_values = self.suggested.arguments.union(
  102. set(self.suggested.defaults or ())
  103. ) - set(self.values.keys())
  104. if missing_values:
  105. message.append(
  106. f" Did you forget to specify values {sorted(missing_values)!r}?"
  107. )
  108. else:
  109. message.append(f" Did you mean {self.suggested.endpoint!r} instead?")
  110. return "".join(message)
  111. class WebsocketMismatch(BadRequest):
  112. """The only matched rule is either a WebSocket and the request is
  113. HTTP, or the rule is HTTP and the request is a WebSocket.
  114. """
  115. class NoMatch(Exception):
  116. __slots__ = ("have_match_for", "websocket_mismatch")
  117. def __init__(self, have_match_for: set[str], websocket_mismatch: bool) -> None:
  118. self.have_match_for = have_match_for
  119. self.websocket_mismatch = websocket_mismatch