exceptions.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. return '%d: %s' % (self.code, self.name)
  126. def __repr__(self):
  127. return '<%s \'%s\'>' % (self.__class__.__name__, self)
  128. class BadRequest(HTTPException):
  129. """*400* `Bad Request`
  130. Raise if the browser sends something to the application the application
  131. or server cannot handle.
  132. """
  133. code = 400
  134. description = (
  135. 'The browser (or proxy) sent a request that this server could '
  136. 'not understand.'
  137. )
  138. class ClientDisconnected(BadRequest):
  139. """Internal exception that is raised if Werkzeug detects a disconnected
  140. client. Since the client is already gone at that point attempting to
  141. send the error message to the client might not work and might ultimately
  142. result in another exception in the server. Mainly this is here so that
  143. it is silenced by default as far as Werkzeug is concerned.
  144. Since disconnections cannot be reliably detected and are unspecified
  145. by WSGI to a large extent this might or might not be raised if a client
  146. is gone.
  147. .. versionadded:: 0.8
  148. """
  149. class SecurityError(BadRequest):
  150. """Raised if something triggers a security error. This is otherwise
  151. exactly like a bad request error.
  152. .. versionadded:: 0.9
  153. """
  154. class BadHost(BadRequest):
  155. """Raised if the submitted host is badly formatted.
  156. .. versionadded:: 0.11.2
  157. """
  158. class Unauthorized(HTTPException):
  159. """*401* `Unauthorized`
  160. Raise if the user is not authorized. Also used if you want to use HTTP
  161. basic auth.
  162. """
  163. code = 401
  164. description = (
  165. 'The server could not verify that you are authorized to access '
  166. 'the URL requested. You either supplied the wrong credentials (e.g. '
  167. 'a bad password), or your browser doesn\'t understand how to supply '
  168. 'the credentials required.'
  169. )
  170. class Forbidden(HTTPException):
  171. """*403* `Forbidden`
  172. Raise if the user doesn't have the permission for the requested resource
  173. but was authenticated.
  174. """
  175. code = 403
  176. description = (
  177. 'You don\'t have the permission to access the requested resource. '
  178. 'It is either read-protected or not readable by the server.'
  179. )
  180. class NotFound(HTTPException):
  181. """*404* `Not Found`
  182. Raise if a resource does not exist and never existed.
  183. """
  184. code = 404
  185. description = (
  186. 'The requested URL was not found on the server. '
  187. 'If you entered the URL manually please check your spelling and '
  188. 'try again.'
  189. )
  190. class MethodNotAllowed(HTTPException):
  191. """*405* `Method Not Allowed`
  192. Raise if the server used a method the resource does not handle. For
  193. example `POST` if the resource is view only. Especially useful for REST.
  194. The first argument for this exception should be a list of allowed methods.
  195. Strictly speaking the response would be invalid if you don't provide valid
  196. methods in the header which you can do with that list.
  197. """
  198. code = 405
  199. description = 'The method is not allowed for the requested URL.'
  200. def __init__(self, valid_methods=None, description=None):
  201. """Takes an optional list of valid http methods
  202. starting with werkzeug 0.3 the list will be mandatory."""
  203. HTTPException.__init__(self, description)
  204. self.valid_methods = valid_methods
  205. def get_headers(self, environ):
  206. headers = HTTPException.get_headers(self, environ)
  207. if self.valid_methods:
  208. headers.append(('Allow', ', '.join(self.valid_methods)))
  209. return headers
  210. class NotAcceptable(HTTPException):
  211. """*406* `Not Acceptable`
  212. Raise if the server can't return any content conforming to the
  213. `Accept` headers of the client.
  214. """
  215. code = 406
  216. description = (
  217. 'The resource identified by the request is only capable of '
  218. 'generating response entities which have content characteristics '
  219. 'not acceptable according to the accept headers sent in the '
  220. 'request.'
  221. )
  222. class RequestTimeout(HTTPException):
  223. """*408* `Request Timeout`
  224. Raise to signalize a timeout.
  225. """
  226. code = 408
  227. description = (
  228. 'The server closed the network connection because the browser '
  229. 'didn\'t finish the request within the specified time.'
  230. )
  231. class Conflict(HTTPException):
  232. """*409* `Conflict`
  233. Raise to signal that a request cannot be completed because it conflicts
  234. with the current state on the server.
  235. .. versionadded:: 0.7
  236. """
  237. code = 409
  238. description = (
  239. 'A conflict happened while processing the request. The resource '
  240. 'might have been modified while the request was being processed.'
  241. )
  242. class Gone(HTTPException):
  243. """*410* `Gone`
  244. Raise if a resource existed previously and went away without new location.
  245. """
  246. code = 410
  247. description = (
  248. 'The requested URL is no longer available on this server and there '
  249. 'is no forwarding address. If you followed a link from a foreign '
  250. 'page, please contact the author of this page.'
  251. )
  252. class LengthRequired(HTTPException):
  253. """*411* `Length Required`
  254. Raise if the browser submitted data but no ``Content-Length`` header which
  255. is required for the kind of processing the server does.
  256. """
  257. code = 411
  258. description = (
  259. 'A request with this method requires a valid <code>Content-'
  260. 'Length</code> header.'
  261. )
  262. class PreconditionFailed(HTTPException):
  263. """*412* `Precondition Failed`
  264. Status code used in combination with ``If-Match``, ``If-None-Match``, or
  265. ``If-Unmodified-Since``.
  266. """
  267. code = 412
  268. description = (
  269. 'The precondition on the request for the URL failed positive '
  270. 'evaluation.'
  271. )
  272. class RequestEntityTooLarge(HTTPException):
  273. """*413* `Request Entity Too Large`
  274. The status code one should return if the data submitted exceeded a given
  275. limit.
  276. """
  277. code = 413
  278. description = (
  279. 'The data value transmitted exceeds the capacity limit.'
  280. )
  281. class RequestURITooLarge(HTTPException):
  282. """*414* `Request URI Too Large`
  283. Like *413* but for too long URLs.
  284. """
  285. code = 414
  286. description = (
  287. 'The length of the requested URL exceeds the capacity limit '
  288. 'for this server. The request cannot be processed.'
  289. )
  290. class UnsupportedMediaType(HTTPException):
  291. """*415* `Unsupported Media Type`
  292. The status code returned if the server is unable to handle the media type
  293. the client transmitted.
  294. """
  295. code = 415
  296. description = (
  297. 'The server does not support the media type transmitted in '
  298. 'the request.'
  299. )
  300. class RequestedRangeNotSatisfiable(HTTPException):
  301. """*416* `Requested Range Not Satisfiable`
  302. The client asked for a part of the file that lies beyond the end
  303. of the file.
  304. .. versionadded:: 0.7
  305. """
  306. code = 416
  307. description = (
  308. 'The server cannot provide the requested range.'
  309. )
  310. class ExpectationFailed(HTTPException):
  311. """*417* `Expectation Failed`
  312. The server cannot meet the requirements of the Expect request-header.
  313. .. versionadded:: 0.7
  314. """
  315. code = 417
  316. description = (
  317. 'The server could not meet the requirements of the Expect header'
  318. )
  319. class ImATeapot(HTTPException):
  320. """*418* `I'm a teapot`
  321. The server should return this if it is a teapot and someone attempted
  322. to brew coffee with it.
  323. .. versionadded:: 0.7
  324. """
  325. code = 418
  326. description = (
  327. 'This server is a teapot, not a coffee machine'
  328. )
  329. class UnprocessableEntity(HTTPException):
  330. """*422* `Unprocessable Entity`
  331. Used if the request is well formed, but the instructions are otherwise
  332. incorrect.
  333. """
  334. code = 422
  335. description = (
  336. 'The request was well-formed but was unable to be followed '
  337. 'due to semantic errors.'
  338. )
  339. class PreconditionRequired(HTTPException):
  340. """*428* `Precondition Required`
  341. The server requires this request to be conditional, typically to prevent
  342. the lost update problem, which is a race condition between two or more
  343. clients attempting to update a resource through PUT or DELETE. By requiring
  344. each client to include a conditional header ("If-Match" or "If-Unmodified-
  345. Since") with the proper value retained from a recent GET request, the
  346. server ensures that each client has at least seen the previous revision of
  347. the resource.
  348. """
  349. code = 428
  350. description = (
  351. 'This request is required to be conditional; try using "If-Match" '
  352. 'or "If-Unmodified-Since".'
  353. )
  354. class TooManyRequests(HTTPException):
  355. """*429* `Too Many Requests`
  356. The server is limiting the rate at which this user receives responses, and
  357. this request exceeds that rate. (The server may use any convenient method
  358. to identify users and their request rates). The server may include a
  359. "Retry-After" header to indicate how long the user should wait before
  360. retrying.
  361. """
  362. code = 429
  363. description = (
  364. 'This user has exceeded an allotted request count. Try again later.'
  365. )
  366. class RequestHeaderFieldsTooLarge(HTTPException):
  367. """*431* `Request Header Fields Too Large`
  368. The server refuses to process the request because the header fields are too
  369. large. One or more individual fields may be too large, or the set of all
  370. headers is too large.
  371. """
  372. code = 431
  373. description = (
  374. 'One or more header fields exceeds the maximum size.'
  375. )
  376. class InternalServerError(HTTPException):
  377. """*500* `Internal Server Error`
  378. Raise if an internal server error occurred. This is a good fallback if an
  379. unknown error occurred in the dispatcher.
  380. """
  381. code = 500
  382. description = (
  383. 'The server encountered an internal error and was unable to '
  384. 'complete your request. Either the server is overloaded or there '
  385. 'is an error in the application.'
  386. )
  387. class NotImplemented(HTTPException):
  388. """*501* `Not Implemented`
  389. Raise if the application does not support the action requested by the
  390. browser.
  391. """
  392. code = 501
  393. description = (
  394. 'The server does not support the action requested by the '
  395. 'browser.'
  396. )
  397. class BadGateway(HTTPException):
  398. """*502* `Bad Gateway`
  399. If you do proxying in your application you should return this status code
  400. if you received an invalid response from the upstream server it accessed
  401. in attempting to fulfill the request.
  402. """
  403. code = 502
  404. description = (
  405. 'The proxy server received an invalid response from an upstream '
  406. 'server.'
  407. )
  408. class ServiceUnavailable(HTTPException):
  409. """*503* `Service Unavailable`
  410. Status code you should return if a service is temporarily unavailable.
  411. """
  412. code = 503
  413. description = (
  414. 'The server is temporarily unable to service your request due to '
  415. 'maintenance downtime or capacity problems. Please try again '
  416. 'later.'
  417. )
  418. class GatewayTimeout(HTTPException):
  419. """*504* `Gateway Timeout`
  420. Status code you should return if a connection to an upstream server
  421. times out.
  422. """
  423. code = 504
  424. description = (
  425. 'The connection to an upstream server timed out.'
  426. )
  427. class HTTPVersionNotSupported(HTTPException):
  428. """*505* `HTTP Version Not Supported`
  429. The server does not support the HTTP protocol version used in the request.
  430. """
  431. code = 505
  432. description = (
  433. 'The server does not support the HTTP protocol version used in the '
  434. 'request.'
  435. )
  436. default_exceptions = {}
  437. __all__ = ['HTTPException']
  438. def _find_exceptions():
  439. for name, obj in iteritems(globals()):
  440. try:
  441. is_http_exception = issubclass(obj, HTTPException)
  442. except TypeError:
  443. is_http_exception = False
  444. if not is_http_exception or obj.code is None:
  445. continue
  446. __all__.append(obj.__name__)
  447. old_obj = default_exceptions.get(obj.code, None)
  448. if old_obj is not None and issubclass(obj, old_obj):
  449. continue
  450. default_exceptions[obj.code] = obj
  451. _find_exceptions()
  452. del _find_exceptions
  453. class Aborter(object):
  454. """
  455. When passed a dict of code -> exception items it can be used as
  456. callable that raises exceptions. If the first argument to the
  457. callable is an integer it will be looked up in the mapping, if it's
  458. a WSGI application it will be raised in a proxy exception.
  459. The rest of the arguments are forwarded to the exception constructor.
  460. """
  461. def __init__(self, mapping=None, extra=None):
  462. if mapping is None:
  463. mapping = default_exceptions
  464. self.mapping = dict(mapping)
  465. if extra is not None:
  466. self.mapping.update(extra)
  467. def __call__(self, code, *args, **kwargs):
  468. if not args and not kwargs and not isinstance(code, integer_types):
  469. raise HTTPException(response=code)
  470. if code not in self.mapping:
  471. raise LookupError('no exception for %r' % code)
  472. raise self.mapping[code](*args, **kwargs)
  473. abort = Aborter()
  474. #: an exception that is used internally to signal both a key error and a
  475. #: bad request. Used by a lot of the datastructures.
  476. BadRequestKeyError = BadRequest.wrap(KeyError)
  477. # imported here because of circular dependencies of werkzeug.utils
  478. from werkzeug.utils import escape
  479. from werkzeug.http import HTTP_STATUS_CODES