exceptions.py 28 KB

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