HTTP Exceptions

优质
小牛编辑
136浏览
2023-12-01

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

Usage Example

from werkzeug.wrappers import BaseRequest
from werkzeug.wsgi import responder
from werkzeug.exceptions import HTTPException, NotFound

def view(request):
    raise NotFound()

@responder
def application(environ, start_response):
    request = BaseRequest(environ)
    try:
        return view(request)
    except HTTPException as e:
        return e

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

As a matter of fact they are not Werkzeug response objects. However you can get a response object by calling get_response() on a HTTP exception.

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

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

@responder
def application(environ, start_response):
    request = BaseRequest(environ)
    try:
        return view(request)
    except NotFound, e:
        return not_found(request)
    except HTTPException, e:
        return e

Error Classes

The following error classes exist in Werkzeug:

exception werkzeug.exceptions.BadRequest(description=None, response=None)

All the exceptions implement this common interface:

exception werkzeug.exceptions.HTTPException(description=None, response=None)

Starting with Werkzeug 0.3 some of the builtin classes raise exceptions that look like regular python exceptions (eg KeyError) but are werkzeug.exceptions.BadRequest" title="werkzeug.exceptions.BadRequest HTTP exceptions at the same time. This decision was made to simplify a common pattern where you want to abort if the client tampered with the submitted form data in a way that the application can’t recover properly and should abort with 400 BAD REQUEST.

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

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

If title or body are missing in the form a special key error will be raised which behaves like a KeyError but also a werkzeug.exceptions.BadRequest" title="werkzeug.exceptions.BadRequest exception.

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 this purpose there is the werkzeug.exceptions.abort" title="werkzeug.exceptions.abort function.

werkzeug.exceptions.abort(status)

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

If you want to add an error yourself you can subclass werkzeug.exceptions.HTTPException" title="werkzeug.exceptions.HTTPException:

from werkzeug.exceptions import HTTPException

class PaymentRequired(HTTPException):
    code = 402
    description = '<p>Payment required.</p>'

This is the minimal code you need for your own exception. If you want to add more logic to the errors you can override the get_description(), get_body(), get_headers() and werkzeug.exceptions.HTTPException.get_response" title="werkzeug.exceptions.HTTPException.get_response methods. In any case you should have a look at the sourcecode of the exceptions module.

You can override the default description in the constructor with the description parameter (it’s the first argument for all exceptions except of the werkzeug.exceptions.MethodNotAllowed" title="werkzeug.exceptions.MethodNotAllowed which accepts a list of allowed methods as first argument):

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