/circuits/web/exceptions.py

https://bitbucket.org/prologic/circuits/ · Python · 315 lines · 253 code · 17 blank · 45 comment · 13 complexity · 449356c98606075dedb619de439ded91 MD5 · raw file

  1. # Module: exceptions
  2. # Date: 10th July 2010
  3. # Author: James Mills, prologic at shortcircuit dot net dot au
  4. """Exceptions
  5. This module implements a set of standard HTTP Errors as Python Exceptions.
  6. Note: This code is mostly borrowed from werkzeug and adapted for circuits.web
  7. """
  8. from inspect import isclass
  9. from .constants import HTTP_STATUS_CODES
  10. class HTTPException(Exception):
  11. """
  12. Baseclass for all HTTP exceptions. This exception can be called by WSGI
  13. applications to render a default error page or you can catch the subclasses
  14. of it independently and render nicer error messages.
  15. """
  16. code = None
  17. traceback = True
  18. description = None
  19. def __init__(self, description=None, traceback=None):
  20. super(HTTPException, self).__init__("%d %s" % (self.code, self.name))
  21. if description is not None:
  22. self.description = description
  23. if traceback is not None:
  24. self.traceback = traceback
  25. @property
  26. def name(self):
  27. """The status name."""
  28. return HTTP_STATUS_CODES.get(self.code, '')
  29. def __repr__(self):
  30. return '<%s \'%s\'>' % (self.__class__.__name__, self)
  31. class BadRequest(HTTPException):
  32. """*400* `Bad Request`
  33. Raise if the browser sends something to the application the application
  34. or server cannot handle.
  35. """
  36. code = 400
  37. description = (
  38. '<p>The browser (or proxy) sent a request that this server could '
  39. 'not understand.</p>'
  40. )
  41. class UnicodeError(HTTPException):
  42. """
  43. raised by the request functions if they were unable to decode the
  44. incoming data properly.
  45. """
  46. class Unauthorized(HTTPException):
  47. """*401* `Unauthorized`
  48. Raise if the user is not authorized. Also used if you want to use HTTP
  49. basic auth.
  50. """
  51. code = 401
  52. description = (
  53. '<p>The server could not verify that you are authorized to access '
  54. 'the URL requested. You either supplied the wrong credentials (e.g. '
  55. 'a bad password), or your browser doesn\'t understand how to supply '
  56. 'the credentials required.</p><p>In case you are allowed to request '
  57. 'the document, please check your user-id and password and try '
  58. 'again.</p>'
  59. )
  60. class Forbidden(HTTPException):
  61. """*403* `Forbidden`
  62. Raise if the user doesn't have the permission for the requested resource
  63. but was authenticated.
  64. """
  65. code = 403
  66. description = (
  67. '<p>You don\'t have the permission to access the requested resource. '
  68. 'It is either read-protected or not readable by the server.</p>'
  69. )
  70. class NotFound(HTTPException):
  71. """*404* `Not Found`
  72. Raise if a resource does not exist and never existed.
  73. """
  74. code = 404
  75. description = (
  76. '<p>The requested URL was not found on the server.</p>'
  77. '<p>If you entered the URL manually please check your spelling and '
  78. 'try again.</p>'
  79. )
  80. class MethodNotAllowed(HTTPException):
  81. """*405* `Method Not Allowed`
  82. Raise if the server used a method the resource does not handle. For
  83. example `POST` if the resource is view only. Especially useful for REST.
  84. The first argument for this exception should be a list of allowed methods.
  85. Strictly speaking the response would be invalid if you don't provide valid
  86. methods in the header which you can do with that list.
  87. """
  88. code = 405
  89. def __init__(self, method, description=None):
  90. HTTPException.__init__(self, description)
  91. if description is None:
  92. self.description = (
  93. '<p>The method %s is not allowed '
  94. 'for the requested URL.</p>'
  95. ) % method
  96. class NotAcceptable(HTTPException):
  97. """*406* `Not Acceptable`
  98. Raise if the server can't return any content conforming to the
  99. `Accept` headers of the client.
  100. """
  101. code = 406
  102. description = (
  103. '<p>The resource identified by the request is only capable of '
  104. 'generating response entities which have content characteristics '
  105. 'not acceptable according to the accept headers sent in the '
  106. 'request.</p>'
  107. )
  108. class RequestTimeout(HTTPException):
  109. """*408* `Request Timeout`
  110. Raise to signalize a timeout.
  111. """
  112. code = 408
  113. description = (
  114. '<p>The server closed the network connection because the browser '
  115. 'didn\'t finish the request within the specified time.</p>'
  116. )
  117. class Gone(HTTPException):
  118. """*410* `Gone`
  119. Raise if a resource existed previously and went away without new location.
  120. """
  121. code = 410
  122. description = (
  123. '<p>The requested URL is no longer available on this server and '
  124. 'there is no forwarding address.</p><p>If you followed a link '
  125. 'from a foreign page, please contact the author of this page.'
  126. )
  127. class LengthRequired(HTTPException):
  128. """*411* `Length Required`
  129. Raise if the browser submitted data but no ``Content-Length`` header which
  130. is required for the kind of processing the server does.
  131. """
  132. code = 411
  133. description = (
  134. '<p>A request with this method requires a valid <code>Content-'
  135. 'Length</code> header.</p>'
  136. )
  137. class PreconditionFailed(HTTPException):
  138. """*412* `Precondition Failed`
  139. Status code used in combination with ``If-Match``, ``If-None-Match``, or
  140. ``If-Unmodified-Since``.
  141. """
  142. code = 412
  143. description = (
  144. '<p>The precondition on the request for the URL failed positive '
  145. 'evaluation.</p>'
  146. )
  147. class RequestEntityTooLarge(HTTPException):
  148. """*413* `Request Entity Too Large`
  149. The status code one should return if the data submitted exceeded a given
  150. limit.
  151. """
  152. code = 413
  153. description = (
  154. '<p>The data value transmitted exceeds the capacity limit.</p>'
  155. )
  156. class RequestURITooLarge(HTTPException):
  157. """*414* `Request URI Too Large`
  158. Like *413* but for too long URLs.
  159. """
  160. code = 414
  161. description = (
  162. '<p>The length of the requested URL exceeds the capacity limit '
  163. 'for this server. The request cannot be processed.</p>'
  164. )
  165. class UnsupportedMediaType(HTTPException):
  166. """*415* `Unsupported Media Type`
  167. The status code returned if the server is unable to handle the media type
  168. the client transmitted.
  169. """
  170. code = 415
  171. description = (
  172. '<p>The server does not support the media type transmitted in '
  173. 'the request.</p>'
  174. )
  175. class RangeUnsatisfiable(HTTPException):
  176. """*416* `Range Unsatisfiable`
  177. The status code returned if the server is unable to satisfy the request range
  178. """
  179. code = 416
  180. description = (
  181. '<p>The server cannot satisfy the request range(s).</p>'
  182. )
  183. class InternalServerError(HTTPException):
  184. """*500* `Internal Server Error`
  185. Raise if an internal server error occurred. This is a good fallback if an
  186. unknown error occurred in the dispatcher.
  187. """
  188. code = 500
  189. description = (
  190. '<p>The server encountered an internal error and was unable to '
  191. 'complete your request. Either the server is overloaded or there '
  192. 'is an error in the application.</p>'
  193. )
  194. class NotImplemented(HTTPException):
  195. """*501* `Not Implemented`
  196. Raise if the application does not support the action requested by the
  197. browser.
  198. """
  199. code = 501
  200. description = (
  201. '<p>The server does not support the action requested by the '
  202. 'browser.</p>'
  203. )
  204. class BadGateway(HTTPException):
  205. """*502* `Bad Gateway`
  206. If you do proxying in your application you should return this status code
  207. if you received an invalid response from the upstream server it accessed
  208. in attempting to fulfill the request.
  209. """
  210. code = 502
  211. description = (
  212. '<p>The proxy server received an invalid response from an upstream '
  213. 'server.</p>'
  214. )
  215. class ServiceUnavailable(HTTPException):
  216. """*503* `Service Unavailable`
  217. Status code you should return if a service is temporarily unavailable.
  218. """
  219. code = 503
  220. description = (
  221. '<p>The server is temporarily unable to service your request due to '
  222. 'maintenance downtime or capacity problems. Please try again '
  223. 'later.</p>'
  224. )
  225. class Redirect(HTTPException):
  226. code = 303
  227. def __init__(self, urls, status=None):
  228. super(Redirect, self).__init__()
  229. if isinstance(urls, str):
  230. self.urls = [urls]
  231. else:
  232. self.urls = urls
  233. self.status = status
  234. __all__ = [
  235. x[0] for x in list(globals().items())
  236. if isclass(x[1]) and issubclass(x[1], HTTPException)
  237. ]