exceptions.py 26 KB

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