exceptions.py 25 KB

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