PageRenderTime 44ms CodeModel.GetById 7ms app.highlight 28ms RepoModel.GetById 2ms app.codeStats 0ms

/circuits/web/exceptions.py

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