HTTP Exceptions

This module implements a number of Python exceptions you can raise fromwithin your views to trigger a standard non-200 response.

Usage Example

  1. from werkzeug.wrappers import BaseRequest
  2. from werkzeug.wsgi import responder
  3. from werkzeug.exceptions import HTTPException, NotFound
  4. def view(request):
  5. raise NotFound()
  6. @responder
  7. def application(environ, start_response):
  8. request = BaseRequest(environ)
  9. try:
  10. return view(request)
  11. except HTTPException as e:
  12. return e

As you can see from this example those exceptions are callable WSGIapplications. Because of Python 2.4 compatibility those do not extendfrom the response objects but only from the python exception class.

As a matter of fact they are not Werkzeug response objects. However youcan get a response object by calling get_response() on a HTTPexception.

Keep in mind that you have to pass an environment to get_response()because some errors fetch additional information from the WSGIenvironment.

If you want to hook in a different exception page to say, a 404 statuscode, you can add a second except for a specific subclass of an error:

  1. @responder
  2. def application(environ, start_response):
  3. request = BaseRequest(environ)
  4. try:
  5. return view(request)
  6. except NotFound, e:
  7. return not_found(request)
  8. except HTTPException, e:
  9. return e

Error Classes

The following error classes exist in Werkzeug:

  • exception _werkzeug.exceptions.BadRequest(_description=None, response=None)
  • 400__Bad Request

Raise if the browser sends something to the application the applicationor server cannot handle.

  • exception _werkzeug.exceptions.Unauthorized(_description=None, response=None)
  • 401__Unauthorized

Raise if the user is not authorized. Also used if you want to use HTTPbasic auth.

  • exception _werkzeug.exceptions.Forbidden(_description=None, response=None)
  • 403__Forbidden

Raise if the user doesn’t have the permission for the requested resourcebut was authenticated.

  • exception _werkzeug.exceptions.NotFound(_description=None, response=None)
  • 404__Not Found

Raise if a resource does not exist and never existed.

  • exception _werkzeug.exceptions.MethodNotAllowed(_valid_methods=None, description=None)
  • 405__Method Not Allowed

Raise if the server used a method the resource does not handle. Forexample POST if the resource is view only. Especially useful for REST.

The first argument for this exception should be a list of allowed methods.Strictly speaking the response would be invalid if you don’t provide validmethods in the header which you can do with that list.

  • exception _werkzeug.exceptions.NotAcceptable(_description=None, response=None)
  • 406__Not Acceptable

Raise if the server can’t return any content conforming to theAccept headers of the client.

  • exception _werkzeug.exceptions.RequestTimeout(_description=None, response=None)
  • 408__Request Timeout

Raise to signalize a timeout.

  • exception _werkzeug.exceptions.Conflict(_description=None, response=None)
  • 409__Conflict

Raise to signal that a request cannot be completed because it conflictswith the current state on the server.

0.7 新版功能.

  • exception _werkzeug.exceptions.Gone(_description=None, response=None)
  • 410__Gone

Raise if a resource existed previously and went away without new location.

  • exception _werkzeug.exceptions.LengthRequired(_description=None, response=None)
  • 411__Length Required

Raise if the browser submitted data but no Content-Length header whichis required for the kind of processing the server does.

  • exception _werkzeug.exceptions.PreconditionFailed(_description=None, response=None)
  • 412__Precondition Failed

Status code used in combination with If-Match, If-None-Match, orIf-Unmodified-Since.

  • exception _werkzeug.exceptions.RequestEntityTooLarge(_description=None, response=None)
  • 413__Request Entity Too Large

The status code one should return if the data submitted exceeded a givenlimit.

  • exception _werkzeug.exceptions.RequestURITooLarge(_description=None, response=None)
  • 414__Request URI Too Large

Like 413 but for too long URLs.

  • exception _werkzeug.exceptions.UnsupportedMediaType(_description=None, response=None)
  • 415__Unsupported Media Type

The status code returned if the server is unable to handle the media typethe client transmitted.

  • exception _werkzeug.exceptions.RequestedRangeNotSatisfiable(_description=None, response=None)
  • 416__Requested Range Not Satisfiable

The client asked for a part of the file that lies beyond the endof the file.

0.7 新版功能.

  • exception _werkzeug.exceptions.ExpectationFailed(_description=None, response=None)
  • 417__Expectation Failed

The server cannot meet the requirements of the Expect request-header.

0.7 新版功能.

  • exception _werkzeug.exceptions.ImATeapot(_description=None, response=None)
  • 418__I’m a teapot

The server should return this if it is a teapot and someone attemptedto brew coffee with it.

0.7 新版功能.

  • exception _werkzeug.exceptions.PreconditionRequired(_description=None, response=None)
  • 428__Precondition Required

The server requires this request to be conditional, typically to preventthe lost update problem, which is a race condition between two or moreclients attempting to update a resource through PUT or DELETE. By requiringeach client to include a conditional header (“If-Match” or “If-Unmodified-Since”) with the proper value retained from a recent GET request, theserver ensures that each client has at least seen the previous revision ofthe resource.

  • exception _werkzeug.exceptions.TooManyRequests(_description=None, response=None)
  • 429__Too Many Requests

The server is limiting the rate at which this user receives responses, andthis request exceeds that rate. (The server may use any convenient methodto identify users and their request rates). The server may include a“Retry-After” header to indicate how long the user should wait beforeretrying.

  • exception _werkzeug.exceptions.RequestHeaderFieldsTooLarge(_description=None, response=None)
  • 431__Request Header Fields Too Large

The server refuses to process the request because the header fields are toolarge. One or more individual fields may be too large, or the set of allheaders is too large.

  • exception _werkzeug.exceptions.InternalServerError(_description=None, response=None)
  • 500__Internal Server Error

Raise if an internal server error occurred. This is a good fallback if anunknown error occurred in the dispatcher.

  • exception _werkzeug.exceptions.NotImplemented(_description=None, response=None)
  • 501__Not Implemented

Raise if the application does not support the action requested by thebrowser.

  • exception _werkzeug.exceptions.BadGateway(_description=None, response=None)
  • 502__Bad Gateway

If you do proxying in your application you should return this status codeif you received an invalid response from the upstream server it accessedin attempting to fulfill the request.

  • exception _werkzeug.exceptions.ServiceUnavailable(_description=None, response=None)
  • 503__Service Unavailable

Status code you should return if a service is temporarily unavailable.

  • _exception _werkzeug.exceptions.HTTPUnicodeError
  • This exception is used to signal unicode decode errors of requestdata. For more information see the Unicode chapter.
  • exception _werkzeug.exceptions.ClientDisconnected(_description=None, response=None)
  • Internal exception that is raised if Werkzeug detects a disconnectedclient. Since the client is already gone at that point attempting tosend the error message to the client might not work and might ultimatelyresult in another exception in the server. Mainly this is here so thatit is silenced by default as far as Werkzeug is concerned.

Since disconnections cannot be reliably detected and are unspecifiedby WSGI to a large extend this might or might not be raised if a clientis gone.

0.8 新版功能.

  • exception _werkzeug.exceptions.SecurityError(_description=None, response=None)
  • Raised if something triggers a security error. This is otherwiseexactly like a bad request error.

0.9 新版功能.

Baseclass

All the exceptions implement this common interface:

  • exception _werkzeug.exceptions.HTTPException(_description=None, response=None)
  • Baseclass for all HTTP exceptions. This exception can be called as WSGIapplication to render a default error page or you can catch the subclassesof it independently and render nicer error messages.

    • call(environ, start_response)
    • Call the exception as WSGI application.

参数:

  1. - **environ** the WSGI environment.
  2. - **start_response** the response callable provided by the WSGIserver.
  • getresponse(_environ=None)
  • Get a response object. If one was passed to the exceptionit’s returned directly.

参数:environ – the optional environ for the request. Thiscan be used to modify the response dependingon how the request looked like.返回:a Response object or a subclass thereof.

Special HTTP Exceptions

Starting with Werkzeug 0.3 some of the builtin classes raise exceptions thatlook like regular python exceptions (eg KeyError) but areBadRequest HTTP exceptions at the same time. This decision was madeto simplify a common pattern where you want to abort if the client tamperedwith the submitted form data in a way that the application can’t recoverproperly and should abort with 400BADREQUEST.

Assuming the application catches all HTTP exceptions and reacts to themproperly a view function could do the following savely and doesn’t have tocheck if the keys exist:

  1. def new_post(request):
  2. post = Post(title=request.form['title'], body=request.form['body'])
  3. post.save()
  4. return redirect(post.url)

If title or body are missing in the form a special key error will beraised which behaves like a KeyError but also a BadRequestexception.

Simple Aborting

Sometimes it’s convenient to just raise an exception by the error code,without importing the exception and looking up the name etc. For thispurpose there is the abort() function.

  • werkzeug.exceptions.abort(status)
  • It can be passed a WSGI application or a status code. If a status codeis given it’s looked up in the list of exceptions from above and willraise that exception, if passed a WSGI application it will wrap it ina proxy WSGI exception and raise that:
  1. abort(404)
  2. abort(Response('Hello World'))

If you want to use this functionality with custom exceptions you cancreate an instance of the aborter class:

  • class _werkzeug.exceptions.Aborter(_mapping=None, extra=None)
  • When passed a dict of code -> exception items it can be used ascallable that raises exceptions. If the first argument to thecallable is an integer it will be looked up in the mapping, if it’sa WSGI application it will be raised in a proxy exception.

The rest of the arguments are forwarded to the exception constructor.

Custom Errors

As you can see from the list above not all status codes are available aserrors. Especially redirects and ather non 200 status codes thatrepresent do not represent errors are missing. For redirects you can usethe redirect() function from the utilities.

If you want to add an error yourself you can subclass HTTPException:

  1. from werkzeug.exceptions import HTTPException
  2. class PaymentRequired(HTTPException):
  3. code = 402
  4. description = '<p>Payment required.</p>'

This is the minimal code you need for your own exception. If you want toadd more logic to the errors you can override theget_description(), get_body(),get_headers() and get_response()methods. In any case you should have a look at the sourcecode of theexceptions module.

You can override the default description in the constructor with thedescription parameter (it’s the first argument for all exceptionsexcept of the MethodNotAllowed which accepts a list of allowed methodsas first argument):

  1. raise BadRequest('Request failed because X was not present')