PageRenderTime 62ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/packages/Werkzeug/werkzeug/exceptions.py

https://github.com/mozilla/doozer-lib
Python | 445 lines | 318 code | 21 blank | 106 comment | 6 complexity | a680096d3736846e0261d76468b1cef2 MD5 | raw file
  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 import BaseRequest, responder
  11. from werkzeug.exceptions import HTTPException, NotFound
  12. def view(request):
  13. raise NotFound()
  14. @responder
  15. def application(environ, start_response):
  16. request = BaseRequest(environ)
  17. try:
  18. return view(request)
  19. except HTTPException, e:
  20. return e
  21. As you can see from this example those exceptions are callable WSGI
  22. applications. Because of Python 2.4 compatibility those do not extend
  23. from the response objects but only from the python exception class.
  24. As a matter of fact they are not Werkzeug response objects. However you
  25. can get a response object by calling ``get_response()`` on a HTTP
  26. exception.
  27. Keep in mind that you have to pass an environment to ``get_response()``
  28. because some errors fetch additional information from the WSGI
  29. environment.
  30. If you want to hook in a different exception page to say, a 404 status
  31. code, you can add a second except for a specific subclass of an error::
  32. @responder
  33. def application(environ, start_response):
  34. request = BaseRequest(environ)
  35. try:
  36. return view(request)
  37. except NotFound, e:
  38. return not_found(request)
  39. except HTTPException, e:
  40. return e
  41. :copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.
  42. :license: BSD, see LICENSE for more details.
  43. """
  44. import sys
  45. from werkzeug._internal import HTTP_STATUS_CODES
  46. class HTTPException(Exception):
  47. """
  48. Baseclass for all HTTP exceptions. This exception can be called as WSGI
  49. application to render a default error page or you can catch the subclasses
  50. of it independently and render nicer error messages.
  51. """
  52. code = None
  53. description = None
  54. def __init__(self, description=None):
  55. Exception.__init__(self, '%d %s' % (self.code, self.name))
  56. if description is not None:
  57. self.description = description
  58. def wrap(cls, exception, name=None):
  59. """
  60. This method returns a new subclass of the exception provided that
  61. also is a subclass of `BadRequest`.
  62. """
  63. class newcls(cls, exception):
  64. def __init__(self, arg=None, description=None):
  65. cls.__init__(self, description)
  66. exception.__init__(self, arg)
  67. newcls.__module__ = sys._getframe(1).f_globals.get('__name__')
  68. newcls.__name__ = name or cls.__name__ + exception.__name__
  69. return newcls
  70. wrap = classmethod(wrap)
  71. def name(self):
  72. """The status name."""
  73. return HTTP_STATUS_CODES[self.code]
  74. name = property(name, doc=name.__doc__)
  75. def get_description(self, environ):
  76. """Get the description."""
  77. return self.description
  78. def get_body(self, environ):
  79. """Get the HTML body."""
  80. return (
  81. '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
  82. '<title>%(code)s %(name)s</title>\n'
  83. '<h1>%(name)s</h1>\n'
  84. '%(description)s\n'
  85. ) % {
  86. 'code': self.code,
  87. 'name': escape(self.name),
  88. 'description': self.get_description(environ)
  89. }
  90. def get_headers(self, environ):
  91. """Get a list of headers."""
  92. return [('Content-Type', 'text/html')]
  93. def get_response(self, environ):
  94. """Get a response object.
  95. :param environ: the environ for the request.
  96. :return: a :class:`BaseResponse` object or a subclass thereof.
  97. """
  98. # lazyly imported for various reasons. For one can use the exceptions
  99. # with custom responses (testing exception instances against types) and
  100. # so we don't ever have to import the wrappers, but also because there
  101. # are ciruclar dependencies when bootstrapping the module.
  102. from werkzeug.wrappers import BaseResponse
  103. headers = self.get_headers(environ)
  104. return BaseResponse(self.get_body(environ), self.code, headers)
  105. def __call__(self, environ, start_response):
  106. """Call the exception as WSGI application.
  107. :param environ: the WSGI environment.
  108. :param start_response: the response callable provided by the WSGI
  109. server.
  110. """
  111. response = self.get_response(environ)
  112. return response(environ, start_response)
  113. class _ProxyException(HTTPException):
  114. """An HTTP exception that expands renders a WSGI application on error."""
  115. def __init__(self, response):
  116. Exception.__init__(self, 'proxy exception for %r' % response)
  117. self.response = response
  118. def get_response(self, environ):
  119. return self.response
  120. class BadRequest(HTTPException):
  121. """*400* `Bad Request`
  122. Raise if the browser sends something to the application the application
  123. or server cannot handle.
  124. """
  125. code = 400
  126. description = (
  127. '<p>The browser (or proxy) sent a request that this server could '
  128. 'not understand.</p>'
  129. )
  130. class Unauthorized(HTTPException):
  131. """*401* `Unauthorized`
  132. Raise if the user is not authorized. Also used if you want to use HTTP
  133. basic auth.
  134. """
  135. code = 401
  136. description = (
  137. '<p>The server could not verify that you are authorized to access '
  138. 'the URL requested. You either supplied the wrong credentials (e.g. '
  139. 'a bad password), or your browser doesn\'t understand how to supply '
  140. 'the credentials required.</p><p>In case you are allowed to request '
  141. 'the document, please check your user-id and password and try '
  142. 'again.</p>'
  143. )
  144. class Forbidden(HTTPException):
  145. """*403* `Forbidden`
  146. Raise if the user doesn't have the permission for the requested resource
  147. but was authenticated.
  148. """
  149. code = 403
  150. description = (
  151. '<p>You don\'t have the permission to access the requested resource. '
  152. 'It is either read-protected or not readable by the server.</p>'
  153. )
  154. class NotFound(HTTPException):
  155. """*404* `Not Found`
  156. Raise if a resource does not exist and never existed.
  157. """
  158. code = 404
  159. description = (
  160. '<p>The requested URL was not found on the server.</p>'
  161. '<p>If you entered the URL manually please check your spelling and '
  162. 'try again.</p>'
  163. )
  164. class MethodNotAllowed(HTTPException):
  165. """*405* `Method Not Allowed`
  166. Raise if the server used a method the resource does not handle. For
  167. example `POST` if the resource is view only. Especially useful for REST.
  168. The first argument for this exception should be a list of allowed methods.
  169. Strictly speaking the response would be invalid if you don't provide valid
  170. methods in the header which you can do with that list.
  171. """
  172. code = 405
  173. def __init__(self, valid_methods=None, description=None):
  174. """Takes an optional list of valid http methods
  175. starting with werkzeug 0.3 the list will be mandatory."""
  176. HTTPException.__init__(self, description)
  177. self.valid_methods = valid_methods
  178. def get_headers(self, environ):
  179. headers = HTTPException.get_headers(self, environ)
  180. if self.valid_methods:
  181. headers.append(('Allow', ', '.join(self.valid_methods)))
  182. return headers
  183. def get_description(self, environ):
  184. m = escape(environ.get('REQUEST_METHOD', 'GET'))
  185. return '<p>The method %s is not allowed for the requested URL.</p>' % m
  186. class NotAcceptable(HTTPException):
  187. """*406* `Not Acceptable`
  188. Raise if the server can't return any content conforming to the
  189. `Accept` headers of the client.
  190. """
  191. code = 406
  192. description = (
  193. '<p>The resource identified by the request is only capable of '
  194. 'generating response entities which have content characteristics '
  195. 'not acceptable according to the accept headers sent in the '
  196. 'request.</p>'
  197. )
  198. class RequestTimeout(HTTPException):
  199. """*408* `Request Timeout`
  200. Raise to signalize a timeout.
  201. """
  202. code = 408
  203. description = (
  204. '<p>The server closed the network connection because the browser '
  205. 'didn\'t finish the request within the specified time.</p>'
  206. )
  207. class Gone(HTTPException):
  208. """*410* `Gone`
  209. Raise if a resource existed previously and went away without new location.
  210. """
  211. code = 410
  212. description = (
  213. '<p>The requested URL is no longer available on this server and '
  214. 'there is no forwarding address.</p><p>If you followed a link '
  215. 'from a foreign page, please contact the author of this page.'
  216. )
  217. class LengthRequired(HTTPException):
  218. """*411* `Length Required`
  219. Raise if the browser submitted data but no ``Content-Length`` header which
  220. is required for the kind of processing the server does.
  221. """
  222. code = 411
  223. description = (
  224. '<p>A request with this method requires a valid <code>Content-'
  225. 'Length</code> header.</p>'
  226. )
  227. class PreconditionFailed(HTTPException):
  228. """*412* `Precondition Failed`
  229. Status code used in combination with ``If-Match``, ``If-None-Match``, or
  230. ``If-Unmodified-Since``.
  231. """
  232. code = 412
  233. description = (
  234. '<p>The precondition on the request for the URL failed positive '
  235. 'evaluation.</p>'
  236. )
  237. class RequestEntityTooLarge(HTTPException):
  238. """*413* `Request Entity Too Large`
  239. The status code one should return if the data submitted exceeded a given
  240. limit.
  241. """
  242. code = 413
  243. description = (
  244. '<p>The data value transmitted exceeds the capacity limit.</p>'
  245. )
  246. class RequestURITooLarge(HTTPException):
  247. """*414* `Request URI Too Large`
  248. Like *413* but for too long URLs.
  249. """
  250. code = 414
  251. description = (
  252. '<p>The length of the requested URL exceeds the capacity limit '
  253. 'for this server. The request cannot be processed.</p>'
  254. )
  255. class UnsupportedMediaType(HTTPException):
  256. """*415* `Unsupported Media Type`
  257. The status code returned if the server is unable to handle the media type
  258. the client transmitted.
  259. """
  260. code = 415
  261. description = (
  262. '<p>The server does not support the media type transmitted in '
  263. 'the request.</p>'
  264. )
  265. class InternalServerError(HTTPException):
  266. """*500* `Internal Server Error`
  267. Raise if an internal server error occurred. This is a good fallback if an
  268. unknown error occurred in the dispatcher.
  269. """
  270. code = 500
  271. description = (
  272. '<p>The server encountered an internal error and was unable to '
  273. 'complete your request. Either the server is overloaded or there '
  274. 'is an error in the application.</p>'
  275. )
  276. class NotImplemented(HTTPException):
  277. """*501* `Not Implemented`
  278. Raise if the application does not support the action requested by the
  279. browser.
  280. """
  281. code = 501
  282. description = (
  283. '<p>The server does not support the action requested by the '
  284. 'browser.</p>'
  285. )
  286. class BadGateway(HTTPException):
  287. """*502* `Bad Gateway`
  288. If you do proxying in your application you should return this status code
  289. if you received an invalid response from the upstream server it accessed
  290. in attempting to fulfill the request.
  291. """
  292. code = 502
  293. description = (
  294. '<p>The proxy server received an invalid response from an upstream '
  295. 'server.</p>'
  296. )
  297. class ServiceUnavailable(HTTPException):
  298. """*503* `Service Unavailable`
  299. Status code you should return if a service is temporarily unavailable.
  300. """
  301. code = 503
  302. description = (
  303. '<p>The server is temporarily unable to service your request due to '
  304. 'maintenance downtime or capacity problems. Please try again '
  305. 'later.</p>'
  306. )
  307. default_exceptions = {}
  308. __all__ = ['HTTPException']
  309. def _find_exceptions():
  310. for name, obj in globals().iteritems():
  311. try:
  312. if getattr(obj, 'code', None) is not None:
  313. default_exceptions[obj.code] = obj
  314. __all__.append(obj.__name__)
  315. except TypeError:
  316. continue
  317. _find_exceptions()
  318. del _find_exceptions
  319. #: raised by the request functions if they were unable to decode the
  320. #: incoming data properly.
  321. HTTPUnicodeError = BadRequest.wrap(UnicodeError, 'HTTPUnicodeError')
  322. class Aborter(object):
  323. """
  324. When passed a dict of code -> exception items it can be used as
  325. callable that raises exceptions. If the first argument to the
  326. callable is a integer it will be looked up in the mapping, if it's
  327. a WSGI application it will be raised in a proxy exception.
  328. The rest of the arguments are forwarded to the exception constructor.
  329. """
  330. def __init__(self, mapping=None, extra=None):
  331. if mapping is None:
  332. mapping = default_exceptions
  333. self.mapping = dict(mapping)
  334. if extra is not None:
  335. self.mapping.update(extra)
  336. def __call__(self, code, *args, **kwargs):
  337. if not args and not kwargs and not isinstance(code, (int, long)):
  338. raise _ProxyException(code)
  339. if code not in self.mapping:
  340. raise LookupError('no exception for %r' % code)
  341. raise self.mapping[code](*args, **kwargs)
  342. abort = Aborter()
  343. # imported here because of circular dependencies of werkzeug.utils
  344. from werkzeug.utils import escape