exceptions.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. """Implements a number of Python exceptions which can be raised from within
  2. a view to trigger a standard HTTP non-200 response.
  3. Usage Example
  4. -------------
  5. .. code-block:: python
  6. from werkzeug.wrappers.request import Request
  7. from werkzeug.exceptions import HTTPException, NotFound
  8. def view(request):
  9. raise NotFound()
  10. @Request.application
  11. def application(request):
  12. try:
  13. return view(request)
  14. except HTTPException as e:
  15. return e
  16. As you can see from this example those exceptions are callable WSGI
  17. applications. However, they are not Werkzeug response objects. You
  18. can get a response object by calling ``get_response()`` on a HTTP
  19. exception.
  20. Keep in mind that you may have to pass an environ (WSGI) or scope
  21. (ASGI) to ``get_response()`` because some errors fetch additional
  22. information relating to the request.
  23. If you want to hook in a different exception page to say, a 404 status
  24. code, you can add a second except for a specific subclass of an error:
  25. .. code-block:: python
  26. @Request.application
  27. def application(request):
  28. try:
  29. return view(request)
  30. except NotFound as e:
  31. return not_found(request)
  32. except HTTPException as e:
  33. return e
  34. """
  35. import typing as t
  36. from datetime import datetime
  37. from html import escape
  38. from ._internal import _get_environ
  39. if t.TYPE_CHECKING:
  40. import typing_extensions as te
  41. from _typeshed.wsgi import StartResponse
  42. from _typeshed.wsgi import WSGIEnvironment
  43. from .datastructures import WWWAuthenticate
  44. from .sansio.response import Response
  45. from .wrappers.request import Request as WSGIRequest # noqa: F401
  46. from .wrappers.response import Response as WSGIResponse # noqa: F401
  47. class HTTPException(Exception):
  48. """The base class for all HTTP exceptions. This exception can be called as a WSGI
  49. application to render a default error page or you can catch the subclasses
  50. of it independently and render nicer error messages.
  51. .. versionchanged:: 2.1
  52. Removed the ``wrap`` class method.
  53. """
  54. code: t.Optional[int] = None
  55. description: t.Optional[str] = None
  56. def __init__(
  57. self,
  58. description: t.Optional[str] = None,
  59. response: t.Optional["Response"] = None,
  60. ) -> None:
  61. super().__init__()
  62. if description is not None:
  63. self.description = description
  64. self.response = response
  65. @property
  66. def name(self) -> str:
  67. """The status name."""
  68. from .http import HTTP_STATUS_CODES
  69. return HTTP_STATUS_CODES.get(self.code, "Unknown Error") # type: ignore
  70. def get_description(
  71. self,
  72. environ: t.Optional["WSGIEnvironment"] = None,
  73. scope: t.Optional[dict] = None,
  74. ) -> str:
  75. """Get the description."""
  76. if self.description is None:
  77. description = ""
  78. elif not isinstance(self.description, str):
  79. description = str(self.description)
  80. else:
  81. description = self.description
  82. description = escape(description).replace("\n", "<br>")
  83. return f"<p>{description}</p>"
  84. def get_body(
  85. self,
  86. environ: t.Optional["WSGIEnvironment"] = None,
  87. scope: t.Optional[dict] = None,
  88. ) -> str:
  89. """Get the HTML body."""
  90. return (
  91. "<!doctype html>\n"
  92. "<html lang=en>\n"
  93. f"<title>{self.code} {escape(self.name)}</title>\n"
  94. f"<h1>{escape(self.name)}</h1>\n"
  95. f"{self.get_description(environ)}\n"
  96. )
  97. def get_headers(
  98. self,
  99. environ: t.Optional["WSGIEnvironment"] = None,
  100. scope: t.Optional[dict] = None,
  101. ) -> t.List[t.Tuple[str, str]]:
  102. """Get a list of headers."""
  103. return [("Content-Type", "text/html; charset=utf-8")]
  104. def get_response(
  105. self,
  106. environ: t.Optional[t.Union["WSGIEnvironment", "WSGIRequest"]] = None,
  107. scope: t.Optional[dict] = None,
  108. ) -> "Response":
  109. """Get a response object. If one was passed to the exception
  110. it's returned directly.
  111. :param environ: the optional environ for the request. This
  112. can be used to modify the response depending
  113. on how the request looked like.
  114. :return: a :class:`Response` object or a subclass thereof.
  115. """
  116. from .wrappers.response import Response as WSGIResponse # noqa: F811
  117. if self.response is not None:
  118. return self.response
  119. if environ is not None:
  120. environ = _get_environ(environ)
  121. headers = self.get_headers(environ, scope)
  122. return WSGIResponse(self.get_body(environ, scope), self.code, headers)
  123. def __call__(
  124. self, environ: "WSGIEnvironment", start_response: "StartResponse"
  125. ) -> t.Iterable[bytes]:
  126. """Call the exception as WSGI application.
  127. :param environ: the WSGI environment.
  128. :param start_response: the response callable provided by the WSGI
  129. server.
  130. """
  131. response = t.cast("WSGIResponse", self.get_response(environ))
  132. return response(environ, start_response)
  133. def __str__(self) -> str:
  134. code = self.code if self.code is not None else "???"
  135. return f"{code} {self.name}: {self.description}"
  136. def __repr__(self) -> str:
  137. code = self.code if self.code is not None else "???"
  138. return f"<{type(self).__name__} '{code}: {self.name}'>"
  139. class BadRequest(HTTPException):
  140. """*400* `Bad Request`
  141. Raise if the browser sends something to the application the application
  142. or server cannot handle.
  143. """
  144. code = 400
  145. description = (
  146. "The browser (or proxy) sent a request that this server could "
  147. "not understand."
  148. )
  149. class BadRequestKeyError(BadRequest, KeyError):
  150. """An exception that is used to signal both a :exc:`KeyError` and a
  151. :exc:`BadRequest`. Used by many of the datastructures.
  152. """
  153. _description = BadRequest.description
  154. #: Show the KeyError along with the HTTP error message in the
  155. #: response. This should be disabled in production, but can be
  156. #: useful in a debug mode.
  157. show_exception = False
  158. def __init__(self, arg: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any):
  159. super().__init__(*args, **kwargs)
  160. if arg is None:
  161. KeyError.__init__(self)
  162. else:
  163. KeyError.__init__(self, arg)
  164. @property # type: ignore
  165. def description(self) -> str: # type: ignore
  166. if self.show_exception:
  167. return (
  168. f"{self._description}\n"
  169. f"{KeyError.__name__}: {KeyError.__str__(self)}"
  170. )
  171. return self._description
  172. @description.setter
  173. def description(self, value: str) -> None:
  174. self._description = value
  175. class ClientDisconnected(BadRequest):
  176. """Internal exception that is raised if Werkzeug detects a disconnected
  177. client. Since the client is already gone at that point attempting to
  178. send the error message to the client might not work and might ultimately
  179. result in another exception in the server. Mainly this is here so that
  180. it is silenced by default as far as Werkzeug is concerned.
  181. Since disconnections cannot be reliably detected and are unspecified
  182. by WSGI to a large extent this might or might not be raised if a client
  183. is gone.
  184. .. versionadded:: 0.8
  185. """
  186. class SecurityError(BadRequest):
  187. """Raised if something triggers a security error. This is otherwise
  188. exactly like a bad request error.
  189. .. versionadded:: 0.9
  190. """
  191. class BadHost(BadRequest):
  192. """Raised if the submitted host is badly formatted.
  193. .. versionadded:: 0.11.2
  194. """
  195. class Unauthorized(HTTPException):
  196. """*401* ``Unauthorized``
  197. Raise if the user is not authorized to access a resource.
  198. The ``www_authenticate`` argument should be used to set the
  199. ``WWW-Authenticate`` header. This is used for HTTP basic auth and
  200. other schemes. Use :class:`~werkzeug.datastructures.WWWAuthenticate`
  201. to create correctly formatted values. Strictly speaking a 401
  202. response is invalid if it doesn't provide at least one value for
  203. this header, although real clients typically don't care.
  204. :param description: Override the default message used for the body
  205. of the response.
  206. :param www-authenticate: A single value, or list of values, for the
  207. WWW-Authenticate header(s).
  208. .. versionchanged:: 2.0
  209. Serialize multiple ``www_authenticate`` items into multiple
  210. ``WWW-Authenticate`` headers, rather than joining them
  211. into a single value, for better interoperability.
  212. .. versionchanged:: 0.15.3
  213. If the ``www_authenticate`` argument is not set, the
  214. ``WWW-Authenticate`` header is not set.
  215. .. versionchanged:: 0.15.3
  216. The ``response`` argument was restored.
  217. .. versionchanged:: 0.15.1
  218. ``description`` was moved back as the first argument, restoring
  219. its previous position.
  220. .. versionchanged:: 0.15.0
  221. ``www_authenticate`` was added as the first argument, ahead of
  222. ``description``.
  223. """
  224. code = 401
  225. description = (
  226. "The server could not verify that you are authorized to access"
  227. " the URL requested. You either supplied the wrong credentials"
  228. " (e.g. a bad password), or your browser doesn't understand"
  229. " how to supply the credentials required."
  230. )
  231. def __init__(
  232. self,
  233. description: t.Optional[str] = None,
  234. response: t.Optional["Response"] = None,
  235. www_authenticate: t.Optional[
  236. t.Union["WWWAuthenticate", t.Iterable["WWWAuthenticate"]]
  237. ] = None,
  238. ) -> None:
  239. super().__init__(description, response)
  240. from .datastructures import WWWAuthenticate
  241. if isinstance(www_authenticate, WWWAuthenticate):
  242. www_authenticate = (www_authenticate,)
  243. self.www_authenticate = www_authenticate
  244. def get_headers(
  245. self,
  246. environ: t.Optional["WSGIEnvironment"] = None,
  247. scope: t.Optional[dict] = None,
  248. ) -> t.List[t.Tuple[str, str]]:
  249. headers = super().get_headers(environ, scope)
  250. if self.www_authenticate:
  251. headers.extend(("WWW-Authenticate", str(x)) for x in self.www_authenticate)
  252. return headers
  253. class Forbidden(HTTPException):
  254. """*403* `Forbidden`
  255. Raise if the user doesn't have the permission for the requested resource
  256. but was authenticated.
  257. """
  258. code = 403
  259. description = (
  260. "You don't have the permission to access the requested"
  261. " resource. It is either read-protected or not readable by the"
  262. " server."
  263. )
  264. class NotFound(HTTPException):
  265. """*404* `Not Found`
  266. Raise if a resource does not exist and never existed.
  267. """
  268. code = 404
  269. description = (
  270. "The requested URL was not found on the server. If you entered"
  271. " the URL manually please check your spelling and try again."
  272. )
  273. class MethodNotAllowed(HTTPException):
  274. """*405* `Method Not Allowed`
  275. Raise if the server used a method the resource does not handle. For
  276. example `POST` if the resource is view only. Especially useful for REST.
  277. The first argument for this exception should be a list of allowed methods.
  278. Strictly speaking the response would be invalid if you don't provide valid
  279. methods in the header which you can do with that list.
  280. """
  281. code = 405
  282. description = "The method is not allowed for the requested URL."
  283. def __init__(
  284. self,
  285. valid_methods: t.Optional[t.Iterable[str]] = None,
  286. description: t.Optional[str] = None,
  287. response: t.Optional["Response"] = None,
  288. ) -> None:
  289. """Takes an optional list of valid http methods
  290. starting with werkzeug 0.3 the list will be mandatory."""
  291. super().__init__(description=description, response=response)
  292. self.valid_methods = valid_methods
  293. def get_headers(
  294. self,
  295. environ: t.Optional["WSGIEnvironment"] = None,
  296. scope: t.Optional[dict] = None,
  297. ) -> t.List[t.Tuple[str, str]]:
  298. headers = super().get_headers(environ, scope)
  299. if self.valid_methods:
  300. headers.append(("Allow", ", ".join(self.valid_methods)))
  301. return headers
  302. class NotAcceptable(HTTPException):
  303. """*406* `Not Acceptable`
  304. Raise if the server can't return any content conforming to the
  305. `Accept` headers of the client.
  306. """
  307. code = 406
  308. description = (
  309. "The resource identified by the request is only capable of"
  310. " generating response entities which have content"
  311. " characteristics not acceptable according to the accept"
  312. " headers sent in the request."
  313. )
  314. class RequestTimeout(HTTPException):
  315. """*408* `Request Timeout`
  316. Raise to signalize a timeout.
  317. """
  318. code = 408
  319. description = (
  320. "The server closed the network connection because the browser"
  321. " didn't finish the request within the specified time."
  322. )
  323. class Conflict(HTTPException):
  324. """*409* `Conflict`
  325. Raise to signal that a request cannot be completed because it conflicts
  326. with the current state on the server.
  327. .. versionadded:: 0.7
  328. """
  329. code = 409
  330. description = (
  331. "A conflict happened while processing the request. The"
  332. " resource might have been modified while the request was being"
  333. " processed."
  334. )
  335. class Gone(HTTPException):
  336. """*410* `Gone`
  337. Raise if a resource existed previously and went away without new location.
  338. """
  339. code = 410
  340. description = (
  341. "The requested URL is no longer available on this server and"
  342. " there is no forwarding address. If you followed a link from a"
  343. " foreign page, please contact the author of this page."
  344. )
  345. class LengthRequired(HTTPException):
  346. """*411* `Length Required`
  347. Raise if the browser submitted data but no ``Content-Length`` header which
  348. is required for the kind of processing the server does.
  349. """
  350. code = 411
  351. description = (
  352. "A request with this method requires a valid <code>Content-"
  353. "Length</code> header."
  354. )
  355. class PreconditionFailed(HTTPException):
  356. """*412* `Precondition Failed`
  357. Status code used in combination with ``If-Match``, ``If-None-Match``, or
  358. ``If-Unmodified-Since``.
  359. """
  360. code = 412
  361. description = (
  362. "The precondition on the request for the URL failed positive evaluation."
  363. )
  364. class RequestEntityTooLarge(HTTPException):
  365. """*413* `Request Entity Too Large`
  366. The status code one should return if the data submitted exceeded a given
  367. limit.
  368. """
  369. code = 413
  370. description = "The data value transmitted exceeds the capacity limit."
  371. class RequestURITooLarge(HTTPException):
  372. """*414* `Request URI Too Large`
  373. Like *413* but for too long URLs.
  374. """
  375. code = 414
  376. description = (
  377. "The length of the requested URL exceeds the capacity limit for"
  378. " this server. The request cannot be processed."
  379. )
  380. class UnsupportedMediaType(HTTPException):
  381. """*415* `Unsupported Media Type`
  382. The status code returned if the server is unable to handle the media type
  383. the client transmitted.
  384. """
  385. code = 415
  386. description = (
  387. "The server does not support the media type transmitted in the request."
  388. )
  389. class RequestedRangeNotSatisfiable(HTTPException):
  390. """*416* `Requested Range Not Satisfiable`
  391. The client asked for an invalid part of the file.
  392. .. versionadded:: 0.7
  393. """
  394. code = 416
  395. description = "The server cannot provide the requested range."
  396. def __init__(
  397. self,
  398. length: t.Optional[int] = None,
  399. units: str = "bytes",
  400. description: t.Optional[str] = None,
  401. response: t.Optional["Response"] = None,
  402. ) -> None:
  403. """Takes an optional `Content-Range` header value based on ``length``
  404. parameter.
  405. """
  406. super().__init__(description=description, response=response)
  407. self.length = length
  408. self.units = units
  409. def get_headers(
  410. self,
  411. environ: t.Optional["WSGIEnvironment"] = None,
  412. scope: t.Optional[dict] = None,
  413. ) -> t.List[t.Tuple[str, str]]:
  414. headers = super().get_headers(environ, scope)
  415. if self.length is not None:
  416. headers.append(("Content-Range", f"{self.units} */{self.length}"))
  417. return headers
  418. class ExpectationFailed(HTTPException):
  419. """*417* `Expectation Failed`
  420. The server cannot meet the requirements of the Expect request-header.
  421. .. versionadded:: 0.7
  422. """
  423. code = 417
  424. description = "The server could not meet the requirements of the Expect header"
  425. class ImATeapot(HTTPException):
  426. """*418* `I'm a teapot`
  427. The server should return this if it is a teapot and someone attempted
  428. to brew coffee with it.
  429. .. versionadded:: 0.7
  430. """
  431. code = 418
  432. description = "This server is a teapot, not a coffee machine"
  433. class UnprocessableEntity(HTTPException):
  434. """*422* `Unprocessable Entity`
  435. Used if the request is well formed, but the instructions are otherwise
  436. incorrect.
  437. """
  438. code = 422
  439. description = (
  440. "The request was well-formed but was unable to be followed due"
  441. " to semantic errors."
  442. )
  443. class Locked(HTTPException):
  444. """*423* `Locked`
  445. Used if the resource that is being accessed is locked.
  446. """
  447. code = 423
  448. description = "The resource that is being accessed is locked."
  449. class FailedDependency(HTTPException):
  450. """*424* `Failed Dependency`
  451. Used if the method could not be performed on the resource
  452. because the requested action depended on another action and that action failed.
  453. """
  454. code = 424
  455. description = (
  456. "The method could not be performed on the resource because the"
  457. " requested action depended on another action and that action"
  458. " failed."
  459. )
  460. class PreconditionRequired(HTTPException):
  461. """*428* `Precondition Required`
  462. The server requires this request to be conditional, typically to prevent
  463. the lost update problem, which is a race condition between two or more
  464. clients attempting to update a resource through PUT or DELETE. By requiring
  465. each client to include a conditional header ("If-Match" or "If-Unmodified-
  466. Since") with the proper value retained from a recent GET request, the
  467. server ensures that each client has at least seen the previous revision of
  468. the resource.
  469. """
  470. code = 428
  471. description = (
  472. "This request is required to be conditional; try using"
  473. ' "If-Match" or "If-Unmodified-Since".'
  474. )
  475. class _RetryAfter(HTTPException):
  476. """Adds an optional ``retry_after`` parameter which will set the
  477. ``Retry-After`` header. May be an :class:`int` number of seconds or
  478. a :class:`~datetime.datetime`.
  479. """
  480. def __init__(
  481. self,
  482. description: t.Optional[str] = None,
  483. response: t.Optional["Response"] = None,
  484. retry_after: t.Optional[t.Union[datetime, int]] = None,
  485. ) -> None:
  486. super().__init__(description, response)
  487. self.retry_after = retry_after
  488. def get_headers(
  489. self,
  490. environ: t.Optional["WSGIEnvironment"] = None,
  491. scope: t.Optional[dict] = None,
  492. ) -> t.List[t.Tuple[str, str]]:
  493. headers = super().get_headers(environ, scope)
  494. if self.retry_after:
  495. if isinstance(self.retry_after, datetime):
  496. from .http import http_date
  497. value = http_date(self.retry_after)
  498. else:
  499. value = str(self.retry_after)
  500. headers.append(("Retry-After", value))
  501. return headers
  502. class TooManyRequests(_RetryAfter):
  503. """*429* `Too Many Requests`
  504. The server is limiting the rate at which this user receives
  505. responses, and this request exceeds that rate. (The server may use
  506. any convenient method to identify users and their request rates).
  507. The server may include a "Retry-After" header to indicate how long
  508. the user should wait before retrying.
  509. :param retry_after: If given, set the ``Retry-After`` header to this
  510. value. May be an :class:`int` number of seconds or a
  511. :class:`~datetime.datetime`.
  512. .. versionchanged:: 1.0
  513. Added ``retry_after`` parameter.
  514. """
  515. code = 429
  516. description = "This user has exceeded an allotted request count. Try again later."
  517. class RequestHeaderFieldsTooLarge(HTTPException):
  518. """*431* `Request Header Fields Too Large`
  519. The server refuses to process the request because the header fields are too
  520. large. One or more individual fields may be too large, or the set of all
  521. headers is too large.
  522. """
  523. code = 431
  524. description = "One or more header fields exceeds the maximum size."
  525. class UnavailableForLegalReasons(HTTPException):
  526. """*451* `Unavailable For Legal Reasons`
  527. This status code indicates that the server is denying access to the
  528. resource as a consequence of a legal demand.
  529. """
  530. code = 451
  531. description = "Unavailable for legal reasons."
  532. class InternalServerError(HTTPException):
  533. """*500* `Internal Server Error`
  534. Raise if an internal server error occurred. This is a good fallback if an
  535. unknown error occurred in the dispatcher.
  536. .. versionchanged:: 1.0.0
  537. Added the :attr:`original_exception` attribute.
  538. """
  539. code = 500
  540. description = (
  541. "The server encountered an internal error and was unable to"
  542. " complete your request. Either the server is overloaded or"
  543. " there is an error in the application."
  544. )
  545. def __init__(
  546. self,
  547. description: t.Optional[str] = None,
  548. response: t.Optional["Response"] = None,
  549. original_exception: t.Optional[BaseException] = None,
  550. ) -> None:
  551. #: The original exception that caused this 500 error. Can be
  552. #: used by frameworks to provide context when handling
  553. #: unexpected errors.
  554. self.original_exception = original_exception
  555. super().__init__(description=description, response=response)
  556. class NotImplemented(HTTPException):
  557. """*501* `Not Implemented`
  558. Raise if the application does not support the action requested by the
  559. browser.
  560. """
  561. code = 501
  562. description = "The server does not support the action requested by the browser."
  563. class BadGateway(HTTPException):
  564. """*502* `Bad Gateway`
  565. If you do proxying in your application you should return this status code
  566. if you received an invalid response from the upstream server it accessed
  567. in attempting to fulfill the request.
  568. """
  569. code = 502
  570. description = (
  571. "The proxy server received an invalid response from an upstream server."
  572. )
  573. class ServiceUnavailable(_RetryAfter):
  574. """*503* `Service Unavailable`
  575. Status code you should return if a service is temporarily
  576. unavailable.
  577. :param retry_after: If given, set the ``Retry-After`` header to this
  578. value. May be an :class:`int` number of seconds or a
  579. :class:`~datetime.datetime`.
  580. .. versionchanged:: 1.0
  581. Added ``retry_after`` parameter.
  582. """
  583. code = 503
  584. description = (
  585. "The server is temporarily unable to service your request due"
  586. " to maintenance downtime or capacity problems. Please try"
  587. " again later."
  588. )
  589. class GatewayTimeout(HTTPException):
  590. """*504* `Gateway Timeout`
  591. Status code you should return if a connection to an upstream server
  592. times out.
  593. """
  594. code = 504
  595. description = "The connection to an upstream server timed out."
  596. class HTTPVersionNotSupported(HTTPException):
  597. """*505* `HTTP Version Not Supported`
  598. The server does not support the HTTP protocol version used in the request.
  599. """
  600. code = 505
  601. description = (
  602. "The server does not support the HTTP protocol version used in the request."
  603. )
  604. default_exceptions: t.Dict[int, t.Type[HTTPException]] = {}
  605. def _find_exceptions() -> None:
  606. for obj in globals().values():
  607. try:
  608. is_http_exception = issubclass(obj, HTTPException)
  609. except TypeError:
  610. is_http_exception = False
  611. if not is_http_exception or obj.code is None:
  612. continue
  613. old_obj = default_exceptions.get(obj.code, None)
  614. if old_obj is not None and issubclass(obj, old_obj):
  615. continue
  616. default_exceptions[obj.code] = obj
  617. _find_exceptions()
  618. del _find_exceptions
  619. class Aborter:
  620. """When passed a dict of code -> exception items it can be used as
  621. callable that raises exceptions. If the first argument to the
  622. callable is an integer it will be looked up in the mapping, if it's
  623. a WSGI application it will be raised in a proxy exception.
  624. The rest of the arguments are forwarded to the exception constructor.
  625. """
  626. def __init__(
  627. self,
  628. mapping: t.Optional[t.Dict[int, t.Type[HTTPException]]] = None,
  629. extra: t.Optional[t.Dict[int, t.Type[HTTPException]]] = None,
  630. ) -> None:
  631. if mapping is None:
  632. mapping = default_exceptions
  633. self.mapping = dict(mapping)
  634. if extra is not None:
  635. self.mapping.update(extra)
  636. def __call__(
  637. self, code: t.Union[int, "Response"], *args: t.Any, **kwargs: t.Any
  638. ) -> "te.NoReturn":
  639. from .sansio.response import Response
  640. if isinstance(code, Response):
  641. raise HTTPException(response=code)
  642. if code not in self.mapping:
  643. raise LookupError(f"no exception for {code!r}")
  644. raise self.mapping[code](*args, **kwargs)
  645. def abort(
  646. status: t.Union[int, "Response"], *args: t.Any, **kwargs: t.Any
  647. ) -> "te.NoReturn":
  648. """Raises an :py:exc:`HTTPException` for the given status code or WSGI
  649. application.
  650. If a status code is given, it will be looked up in the list of
  651. exceptions and will raise that exception. If passed a WSGI application,
  652. it will wrap it in a proxy WSGI exception and raise that::
  653. abort(404) # 404 Not Found
  654. abort(Response('Hello World'))
  655. """
  656. _aborter(status, *args, **kwargs)
  657. _aborter: Aborter = Aborter()