exceptions.py 20 KB

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