Web Server Exceptions

Overview

aiohttp.web defines a set of exceptions for every HTTP status code.

Each exception is a subclass of HTTPException and relates to a single HTTP status code:

async def handler(request):
    raise aiohttp.web.HTTPFound('/redirect')

Each exception class has a status code according to RFC 2068: codes with 100-300 are not really errors; 400s are client errors, and 500s are server errors.

HTTP Exception hierarchy chart:

Exception
  HTTPException
    HTTPSuccessful
      * 200 - HTTPOk
      * 201 - HTTPCreated
      * 202 - HTTPAccepted
      * 203 - HTTPNonAuthoritativeInformation
      * 204 - HTTPNoContent
      * 205 - HTTPResetContent
      * 206 - HTTPPartialContent
    HTTPRedirection
      * 304 - HTTPNotModified
      HTTPMove
        * 300 - HTTPMultipleChoices
        * 301 - HTTPMovedPermanently
        * 302 - HTTPFound
        * 303 - HTTPSeeOther
        * 305 - HTTPUseProxy
        * 307 - HTTPTemporaryRedirect
        * 308 - HTTPPermanentRedirect
    HTTPError
      HTTPClientError
        * 400 - HTTPBadRequest
        * 401 - HTTPUnauthorized
        * 402 - HTTPPaymentRequired
        * 403 - HTTPForbidden
        * 404 - HTTPNotFound
        * 405 - HTTPMethodNotAllowed
        * 406 - HTTPNotAcceptable
        * 407 - HTTPProxyAuthenticationRequired
        * 408 - HTTPRequestTimeout
        * 409 - HTTPConflict
        * 410 - HTTPGone
        * 411 - HTTPLengthRequired
        * 412 - HTTPPreconditionFailed
        * 413 - HTTPRequestEntityTooLarge
        * 414 - HTTPRequestURITooLong
        * 415 - HTTPUnsupportedMediaType
        * 416 - HTTPRequestRangeNotSatisfiable
        * 417 - HTTPExpectationFailed
        * 421 - HTTPMisdirectedRequest
        * 422 - HTTPUnprocessableEntity
        * 424 - HTTPFailedDependency
        * 426 - HTTPUpgradeRequired
        * 428 - HTTPPreconditionRequired
        * 429 - HTTPTooManyRequests
        * 431 - HTTPRequestHeaderFieldsTooLarge
        * 451 - HTTPUnavailableForLegalReasons
      HTTPServerError
        * 500 - HTTPInternalServerError
        * 501 - HTTPNotImplemented
        * 502 - HTTPBadGateway
        * 503 - HTTPServiceUnavailable
        * 504 - HTTPGatewayTimeout
        * 505 - HTTPVersionNotSupported
        * 506 - HTTPVariantAlsoNegotiates
        * 507 - HTTPInsufficientStorage
        * 510 - HTTPNotExtended
        * 511 - HTTPNetworkAuthenticationRequired

All HTTP exceptions have the same constructor signature:

HTTPNotFound(*, headers=None, reason=None,
             text=None, content_type=None)

If not directly specified, headers will be added to the default response headers.

Classes HTTPMultipleChoices, HTTPMovedPermanently, HTTPFound, HTTPSeeOther, HTTPUseProxy, HTTPTemporaryRedirect have the following constructor signature:

HTTPFound(location, *,headers=None, reason=None,
          text=None, content_type=None)

where location is value for Location HTTP header.

HTTPMethodNotAllowed is constructed by providing the incoming unsupported method and list of allowed methods:

HTTPMethodNotAllowed(method, allowed_methods, *,
                     headers=None, reason=None,
                     text=None, content_type=None)

HTTPUnavailableForLegalReasons should be constructed with a link to yourself (as the entity implementing the blockage), and an explanation for the block included in text.:

HTTPUnavailableForLegalReasons(link, *,
                               headers=None, reason=None,
                               text=None, content_type=None)

Base HTTP Exception

exception aiohttp.web.HTTPException(*, headers=None, reason=None, text=None, content_type=None)[source]

The base class for HTTP server exceptions. Inherited from Exception.

Parameters:
  • headers – HTTP headers (Mapping)

  • reason (str) – an optional custom HTTP reason. aiohttp uses default reason string if not specified.

  • text (str) – an optional text used in response body. If not specified default text is constructed from status code and reason, e.g. “404: Not Found”.

  • content_type (str) – an optional Content-Type, “text/plain” by default.

status

HTTP status code for the exception, int

reason

HTTP status reason for the exception, str

text

HTTP status reason for the exception, str or None for HTTP exceptions without body, e.g. “204 No Content”

headers

HTTP headers for the exception, multidict.CIMultiDict

cookies

An instance of http.cookies.SimpleCookie for outgoing cookies.

Added in version 4.0.

Convenient way for setting cookies, allows to specify some additional properties like max_age in a single call.

Added in version 4.0.

Parameters:
  • name (str) – cookie name

  • value (str) – cookie value (will be converted to str if value has another type).

  • expires – expiration date (optional)

  • domain (str) – cookie domain (optional)

  • max_age (int) – defines the lifetime of the cookie, in seconds. The delta-seconds value is a decimal non- negative integer. After delta-seconds seconds elapse, the client should discard the cookie. A value of zero means the cookie should be discarded immediately. (optional)

  • path (str) – specifies the subset of URLs to which this cookie applies. (optional, '/' by default)

  • secure (bool) – attribute (with no value) directs the user agent to use only (unspecified) secure means to contact the origin server whenever it sends back this cookie. The user agent (possibly under the user’s control) may determine what level of security it considers appropriate for “secure” cookies. The secure should be considered security advice from the server to the user agent, indicating that it is in the session’s interest to protect the cookie contents. (optional)

  • httponly (bool) – True if the cookie HTTP only (optional)

  • version (int) – a decimal integer, identifies to which version of the state management specification the cookie conforms. (Optional, version=1 by default)

  • samesite (str) – Asserts that a cookie must not be sent with cross-origin requests, providing some protection against cross-site request forgery attacks. Generally the value should be one of: None, Lax or Strict. (optional)

Warning

In HTTP version 1.1, expires was deprecated and replaced with the easier-to-use max-age, but Internet Explorer (IE6, IE7, and IE8) does not support max-age.

Deletes cookie.

Added in version 4.0.

Parameters:
  • name (str) – cookie name

  • domain (str) – optional cookie domain

  • path (str) – optional cookie path, '/' by default

Successful Exceptions

HTTP exceptions for status code in range 200-299. They are not errors but special classes reflected in exceptions hierarchy. E.g. raise web.HTTPNoContent may look strange a little but the construction is absolutely legal.

exception aiohttp.web.HTTPSuccessful[source]

A base class for the category, a subclass of HTTPException.

exception aiohttp.web.HTTPOk[source]

An exception for 200 OK, a subclass of HTTPSuccessful.

exception aiohttp.web.HTTPCreated[source]

An exception for 201 Created, a subclass of HTTPSuccessful.

exception aiohttp.web.HTTPAccepted[source]

An exception for 202 Accepted, a subclass of HTTPSuccessful.

exception aiohttp.web.HTTPNonAuthoritativeInformation[source]

An exception for 203 Non-Authoritative Information, a subclass of HTTPSuccessful.

exception aiohttp.web.HTTPNoContent[source]

An exception for 204 No Content, a subclass of HTTPSuccessful.

Has no HTTP body.

exception aiohttp.web.HTTPResetContent[source]

An exception for 205 Reset Content, a subclass of HTTPSuccessful.

Has no HTTP body.

exception aiohttp.web.HTTPPartialContent[source]

An exception for 206 Partial Content, a subclass of HTTPSuccessful.

Redirections

HTTP exceptions for status code in range 300-399, e.g. raise web.HTTPMovedPermanently(location='/new/path').

exception aiohttp.web.HTTPRedirection[source]

A base class for the category, a subclass of HTTPException.

exception aiohttp.web.HTTPMove(location, *, headers=None, reason=None, text=None, content_type=None)[source]

A base class for redirections with implied Location header, all redirections except HTTPNotModified.

Parameters:

location – a yarl.URL or str used for Location HTTP header.

For other arguments see HTTPException constructor.

location

A Location HTTP header value, yarl.URL.

exception aiohttp.web.HTTPMultipleChoices[source]

An exception for 300 Multiple Choices, a subclass of HTTPMove.

exception aiohttp.web.HTTPMovedPermanently[source]

An exception for 301 Moved Permanently, a subclass of HTTPMove.

exception aiohttp.web.HTTPFound[source]

An exception for 302 Found, a subclass of HTTPMove.

exception aiohttp.web.HTTPSeeOther[source]

An exception for 303 See Other, a subclass of HTTPMove.

exception aiohttp.web.HTTPNotModified[source]

An exception for 304 Not Modified, a subclass of HTTPRedirection.

Has no HTTP body.

exception aiohttp.web.HTTPUseProxy[source]

An exception for 305 Use Proxy, a subclass of HTTPMove.

exception aiohttp.web.HTTPTemporaryRedirect[source]

An exception for 307 Temporary Redirect, a subclass of HTTPMove.

exception aiohttp.web.HTTPPermanentRedirect[source]

An exception for 308 Permanent Redirect, a subclass of HTTPMove.

Client Errors

HTTP exceptions for status code in range 400-499, e.g. raise web.HTTPNotFound().

exception aiohttp.web.HTTPClientError[source]

A base class for the category, a subclass of HTTPException.

exception aiohttp.web.HTTPBadRequest[source]

An exception for 400 Bad Request, a subclass of HTTPClientError.

exception aiohttp.web.HTTPUnauthorized[source]

An exception for 401 Unauthorized, a subclass of HTTPClientError.

exception aiohttp.web.HTTPPaymentRequired[source]

An exception for 402 Payment Required, a subclass of HTTPClientError.

exception aiohttp.web.HTTPForbidden[source]

An exception for 403 Forbidden, a subclass of HTTPClientError.

exception aiohttp.web.HTTPNotFound[source]

An exception for 404 Not Found, a subclass of HTTPClientError.

exception aiohttp.web.HTTPMethodNotAllowed(method, allowed_methods, *, headers=None, reason=None, text=None, content_type=None)[source]

An exception for 405 Method Not Allowed, a subclass of HTTPClientError.

Parameters:
  • method (str) – requested but not allowed HTTP method.

  • allowed_methods – an iterable of allowed HTTP methods (str), Allow HTTP header is constructed from the sequence separated by comma.

For other arguments see HTTPException constructor.

allowed_methods

A set of allowed HTTP methods.

method

Requested but not allowed HTTP method.

exception aiohttp.web.HTTPNotAcceptable[source]

An exception for 406 Not Acceptable, a subclass of HTTPClientError.

exception aiohttp.web.HTTPProxyAuthenticationRequired[source]

An exception for 407 Proxy Authentication Required, a subclass of HTTPClientError.

exception aiohttp.web.HTTPRequestTimeout[source]

An exception for 408 Request Timeout, a subclass of HTTPClientError.

exception aiohttp.web.HTTPConflict[source]

An exception for 409 Conflict, a subclass of HTTPClientError.

exception aiohttp.web.HTTPGone[source]

An exception for 410 Gone, a subclass of HTTPClientError.

exception aiohttp.web.HTTPLengthRequired[source]

An exception for 411 Length Required, a subclass of HTTPClientError.

exception aiohttp.web.HTTPPreconditionFailed[source]

An exception for 412 Precondition Failed, a subclass of HTTPClientError.

exception aiohttp.web.HTTPRequestEntityTooLarge(max_size, actual_size, **kwargs)[source]

An exception for 413 Entity Too Large, a subclass of HTTPClientError.

Parameters:
  • max_size (int) – Maximum allowed request body size

  • actual_size (int) – Actual received size

For other acceptable parameters see HTTPException constructor.

exception aiohttp.web.HTTPRequestURITooLong[source]

An exception for 414 URI is too long, a subclass of HTTPClientError.

exception aiohttp.web.HTTPUnsupportedMediaType[source]

An exception for 415 Entity body in unsupported format, a subclass of HTTPClientError.

exception aiohttp.web.HTTPRequestRangeNotSatisfiable[source]

An exception for 416 Cannot satisfy request range, a subclass of HTTPClientError.

exception aiohttp.web.HTTPExpectationFailed[source]

An exception for 417 Expect condition could not be satisfied, a subclass of HTTPClientError.

exception aiohttp.web.HTTPMisdirectedRequest[source]

An exception for 421 Misdirected Request, a subclass of HTTPClientError.

exception aiohttp.web.HTTPUnprocessableEntity[source]

An exception for 422 Unprocessable Entity, a subclass of HTTPClientError.

exception aiohttp.web.HTTPFailedDependency[source]

An exception for 424 Failed Dependency, a subclass of HTTPClientError.

exception aiohttp.web.HTTPUpgradeRequired[source]

An exception for 426 Upgrade Required, a subclass of HTTPClientError.

exception aiohttp.web.HTTPPreconditionRequired[source]

An exception for 428 Precondition Required, a subclass of HTTPClientError.

exception aiohttp.web.HTTPTooManyRequests[source]

An exception for 429 Too Many Requests, a subclass of HTTPClientError.

exception aiohttp.web.HTTPRequestHeaderFieldsTooLarge[source]

An exception for 431 Requests Header Fields Too Large, a subclass of HTTPClientError.

exception aiohttp.web.HTTPUnavailableForLegalReasons(link, *, headers=None, reason=None, text=None, content_type=None)[source]

An exception for 451 Unavailable For Legal Reasons, a subclass of HTTPClientError.

Parameters:

link – A link to yourself (as the entity implementing the blockage), str, URL or None.

For other parameters see HTTPException constructor. A reason for the block should be included in text.

A URL link to the entity implementing the blockage or None, read-only property.

Server Errors

HTTP exceptions for status code in range 500-599, e.g. raise web.HTTPBadGateway().

exception aiohttp.web.HTTPServerError[source]

A base class for the category, a subclass of HTTPException.

exception aiohttp.web.HTTPInternalServerError[source]

An exception for 500 Server got itself in trouble, a subclass of HTTPServerError.

exception aiohttp.web.HTTPNotImplemented[source]

An exception for 501 Server does not support this operation, a subclass of HTTPServerError.

exception aiohttp.web.HTTPBadGateway[source]

An exception for 502 Invalid responses from another server/proxy, a subclass of HTTPServerError.

exception aiohttp.web.HTTPServiceUnavailable[source]

An exception for 503 The server cannot process the request due to a high load, a subclass of HTTPServerError.

exception aiohttp.web.HTTPGatewayTimeout[source]

An exception for 504 The gateway server did not receive a timely response, a subclass of HTTPServerError.

exception aiohttp.web.HTTPVersionNotSupported[source]

An exception for 505 Cannot fulfill request, a subclass of HTTPServerError.

exception aiohttp.web.HTTPVariantAlsoNegotiates[source]

An exception for 506 Variant Also Negotiates, a subclass of HTTPServerError.

exception aiohttp.web.HTTPInsufficientStorage[source]

An exception for 507 Insufficient Storage, a subclass of HTTPServerError.

exception aiohttp.web.HTTPNotExtended[source]

An exception for 510 Not Extended, a subclass of HTTPServerError.

exception aiohttp.web.HTTPNetworkAuthenticationRequired[source]

An exception for 511 Network Authentication Required, a subclass of HTTPServerError.