exceptions.py 26 KB

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