You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

exceptions.py 23KB

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