exceptions.py 4.6 KB

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