exceptions.py 28 KB

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