1 """Implements a number of Python exceptions which can be raised from within
2 a view to trigger a standard HTTP non-200 response.
9 from werkzeug.wrappers.request import Request
10 from werkzeug.exceptions import HTTPException, NotFound
16 def application(request):
19 except HTTPException as e:
22 As you can see from this example those exceptions are callable WSGI
23 applications. However, they are not Werkzeug response objects. You
24 can get a response object by calling ``get_response()`` on a HTTP
27 Keep in mind that you may have to pass an environ (WSGI) or scope
28 (ASGI) to ``get_response()`` because some errors fetch additional
29 information relating to the request.
31 If you want to hook in a different exception page to say, a 404 status
32 code, you can add a second except for a specific subclass of an error:
34 .. code-block:: python
37 def application(request):
41 return not_found(request)
42 except HTTPException as e:
46 from __future__
import annotations
49 from datetime
import datetime
51 from markupsafe
import escape
52 from markupsafe
import Markup
54 from ._internal
import _get_environ
57 from _typeshed
.wsgi
import StartResponse
58 from _typeshed
.wsgi
import WSGIEnvironment
59 from .datastructures
import WWWAuthenticate
60 from .sansio
.response
import Response
61 from .wrappers
.request
import Request
as WSGIRequest
62 from .wrappers
.response
import Response
as WSGIResponse
65 class HTTPException(Exception):
66 """The base class for all HTTP exceptions. This exception can be called as a WSGI
67 application to render a default error page or you can catch the subclasses
68 of it independently and render nicer error messages.
70 .. versionchanged:: 2.1
71 Removed the ``wrap`` class method.
74 code
: int |
None = None
75 description
: str |
None = None
79 description
: str |
None = None,
80 response
: Response |
None = None,
83 if description
is not None:
84 self
.description
= description
85 self
.response
= response
88 def name(self
) -> str:
89 """The status name."""
90 from .http
import HTTP_STATUS_CODES
92 return HTTP_STATUS_CODES
.get(self
.code
, "Unknown Error") # type: ignore
96 environ
: WSGIEnvironment |
None = None,
97 scope
: dict |
None = None,
99 """Get the description."""
100 if self
.description
is None:
103 description
= self
.description
105 description
= escape(description
).replace("\n", Markup("<br>"))
106 return f
"<p>{description}</p>"
110 environ
: WSGIEnvironment |
None = None,
111 scope
: dict |
None = None,
113 """Get the HTML body."""
117 f
"<title>{self.code} {escape(self.name)}</title>\n"
118 f
"<h1>{escape(self.name)}</h1>\n"
119 f
"{self.get_description(environ)}\n"
124 environ
: WSGIEnvironment |
None = None,
125 scope
: dict |
None = None,
126 ) -> list[tuple[str, str]]:
127 """Get a list of headers."""
128 return [("Content-Type", "text/html; charset=utf-8")]
132 environ
: WSGIEnvironment | WSGIRequest |
None = None,
133 scope
: dict |
None = None,
135 """Get a response object. If one was passed to the exception
136 it's returned directly.
138 :param environ: the optional environ for the request. This
139 can be used to modify the response depending
140 on how the request looked like.
141 :return: a :class:`Response` object or a subclass thereof.
143 from .wrappers
.response
import Response
as WSGIResponse
# noqa: F811
145 if self
.response
is not None:
147 if environ
is not None:
148 environ
= _get_environ(environ
)
149 headers
= self
.get_headers(environ
, scope
)
150 return WSGIResponse(self
.get_body(environ
, scope
), self
.code
, headers
)
153 self
, environ
: WSGIEnvironment
, start_response
: StartResponse
154 ) -> t
.Iterable
[bytes]:
155 """Call the exception as WSGI application.
157 :param environ: the WSGI environment.
158 :param start_response: the response callable provided by the WSGI
161 response
= t
.cast("WSGIResponse", self
.get_response(environ
))
162 return response(environ
, start_response
)
164 def __str__(self
) -> str:
165 code
= self
.code
if self
.code
is not None else "???"
166 return f
"{code} {self.name}: {self.description}"
168 def __repr__(self
) -> str:
169 code
= self
.code
if self
.code
is not None else "???"
170 return f
"<{type(self).__name__} '{code}: {self.name}'>"
173 class BadRequest(HTTPException
):
174 """*400* `Bad Request`
176 Raise if the browser sends something to the application the application
177 or server cannot handle.
182 "The browser (or proxy) sent a request that this server could "
187 class BadRequestKeyError(BadRequest
, KeyError):
188 """An exception that is used to signal both a :exc:`KeyError` and a
189 :exc:`BadRequest`. Used by many of the datastructures.
192 _description
= BadRequest
.description
193 #: Show the KeyError along with the HTTP error message in the
194 #: response. This should be disabled in production, but can be
195 #: useful in a debug mode.
196 show_exception
= False
198 def __init__(self
, arg
: str |
None = None, *args
: t
.Any
, **kwargs
: t
.Any
):
199 super().__init
__(*args
, **kwargs
)
202 KeyError.__init
__(self
)
204 KeyError.__init
__(self
, arg
)
206 @property # type: ignore
207 def description(self
) -> str:
208 if self
.show_exception
:
210 f
"{self._description}\n"
211 f
"{KeyError.__name__}: {KeyError.__str__(self)}"
214 return self
._description
217 def description(self
, value
: str) -> None:
218 self
._description
= value
221 class ClientDisconnected(BadRequest
):
222 """Internal exception that is raised if Werkzeug detects a disconnected
223 client. Since the client is already gone at that point attempting to
224 send the error message to the client might not work and might ultimately
225 result in another exception in the server. Mainly this is here so that
226 it is silenced by default as far as Werkzeug is concerned.
228 Since disconnections cannot be reliably detected and are unspecified
229 by WSGI to a large extent this might or might not be raised if a client
232 .. versionadded:: 0.8
236 class SecurityError(BadRequest
):
237 """Raised if something triggers a security error. This is otherwise
238 exactly like a bad request error.
240 .. versionadded:: 0.9
244 class BadHost(BadRequest
):
245 """Raised if the submitted host is badly formatted.
247 .. versionadded:: 0.11.2
251 class Unauthorized(HTTPException
):
252 """*401* ``Unauthorized``
254 Raise if the user is not authorized to access a resource.
256 The ``www_authenticate`` argument should be used to set the
257 ``WWW-Authenticate`` header. This is used for HTTP basic auth and
258 other schemes. Use :class:`~werkzeug.datastructures.WWWAuthenticate`
259 to create correctly formatted values. Strictly speaking a 401
260 response is invalid if it doesn't provide at least one value for
261 this header, although real clients typically don't care.
263 :param description: Override the default message used for the body
265 :param www-authenticate: A single value, or list of values, for the
266 WWW-Authenticate header(s).
268 .. versionchanged:: 2.0
269 Serialize multiple ``www_authenticate`` items into multiple
270 ``WWW-Authenticate`` headers, rather than joining them
271 into a single value, for better interoperability.
273 .. versionchanged:: 0.15.3
274 If the ``www_authenticate`` argument is not set, the
275 ``WWW-Authenticate`` header is not set.
277 .. versionchanged:: 0.15.3
278 The ``response`` argument was restored.
280 .. versionchanged:: 0.15.1
281 ``description`` was moved back as the first argument, restoring
282 its previous position.
284 .. versionchanged:: 0.15.0
285 ``www_authenticate`` was added as the first argument, ahead of
291 "The server could not verify that you are authorized to access"
292 " the URL requested. You either supplied the wrong credentials"
293 " (e.g. a bad password), or your browser doesn't understand"
294 " how to supply the credentials required."
299 description
: str |
None = None,
300 response
: Response |
None = None,
301 www_authenticate
: None |
(WWWAuthenticate | t
.Iterable
[WWWAuthenticate
]) = None,
303 super().__init
__(description
, response
)
305 from .datastructures
import WWWAuthenticate
307 if isinstance(www_authenticate
, WWWAuthenticate
):
308 www_authenticate
= (www_authenticate
,)
310 self
.www_authenticate
= www_authenticate
314 environ
: WSGIEnvironment |
None = None,
315 scope
: dict |
None = None,
316 ) -> list[tuple[str, str]]:
317 headers
= super().get_headers(environ
, scope
)
318 if self
.www_authenticate
:
319 headers
.extend(("WWW-Authenticate", str(x
)) for x
in self
.www_authenticate
)
323 class Forbidden(HTTPException
):
326 Raise if the user doesn't have the permission for the requested resource
327 but was authenticated.
332 "You don't have the permission to access the requested"
333 " resource. It is either read-protected or not readable by the"
338 class NotFound(HTTPException
):
341 Raise if a resource does not exist and never existed.
346 "The requested URL was not found on the server. If you entered"
347 " the URL manually please check your spelling and try again."
351 class MethodNotAllowed(HTTPException
):
352 """*405* `Method Not Allowed`
354 Raise if the server used a method the resource does not handle. For
355 example `POST` if the resource is view only. Especially useful for REST.
357 The first argument for this exception should be a list of allowed methods.
358 Strictly speaking the response would be invalid if you don't provide valid
359 methods in the header which you can do with that list.
363 description
= "The method is not allowed for the requested URL."
367 valid_methods
: t
.Iterable
[str] |
None = None,
368 description
: str |
None = None,
369 response
: Response |
None = None,
371 """Takes an optional list of valid http methods
372 starting with werkzeug 0.3 the list will be mandatory."""
373 super().__init
__(description
=description
, response
=response
)
374 self
.valid_methods
= valid_methods
378 environ
: WSGIEnvironment |
None = None,
379 scope
: dict |
None = None,
380 ) -> list[tuple[str, str]]:
381 headers
= super().get_headers(environ
, scope
)
382 if self
.valid_methods
:
383 headers
.append(("Allow", ", ".join(self
.valid_methods
)))
387 class NotAcceptable(HTTPException
):
388 """*406* `Not Acceptable`
390 Raise if the server can't return any content conforming to the
391 `Accept` headers of the client.
396 "The resource identified by the request is only capable of"
397 " generating response entities which have content"
398 " characteristics not acceptable according to the accept"
399 " headers sent in the request."
403 class RequestTimeout(HTTPException
):
404 """*408* `Request Timeout`
406 Raise to signalize a timeout.
411 "The server closed the network connection because the browser"
412 " didn't finish the request within the specified time."
416 class Conflict(HTTPException
):
419 Raise to signal that a request cannot be completed because it conflicts
420 with the current state on the server.
422 .. versionadded:: 0.7
427 "A conflict happened while processing the request. The"
428 " resource might have been modified while the request was being"
433 class Gone(HTTPException
):
436 Raise if a resource existed previously and went away without new location.
441 "The requested URL is no longer available on this server and"
442 " there is no forwarding address. If you followed a link from a"
443 " foreign page, please contact the author of this page."
447 class LengthRequired(HTTPException
):
448 """*411* `Length Required`
450 Raise if the browser submitted data but no ``Content-Length`` header which
451 is required for the kind of processing the server does.
456 "A request with this method requires a valid <code>Content-"
457 "Length</code> header."
461 class PreconditionFailed(HTTPException
):
462 """*412* `Precondition Failed`
464 Status code used in combination with ``If-Match``, ``If-None-Match``, or
465 ``If-Unmodified-Since``.
470 "The precondition on the request for the URL failed positive evaluation."
474 class RequestEntityTooLarge(HTTPException
):
475 """*413* `Request Entity Too Large`
477 The status code one should return if the data submitted exceeded a given
482 description
= "The data value transmitted exceeds the capacity limit."
485 class RequestURITooLarge(HTTPException
):
486 """*414* `Request URI Too Large`
488 Like *413* but for too long URLs.
493 "The length of the requested URL exceeds the capacity limit for"
494 " this server. The request cannot be processed."
498 class UnsupportedMediaType(HTTPException
):
499 """*415* `Unsupported Media Type`
501 The status code returned if the server is unable to handle the media type
502 the client transmitted.
507 "The server does not support the media type transmitted in the request."
511 class RequestedRangeNotSatisfiable(HTTPException
):
512 """*416* `Requested Range Not Satisfiable`
514 The client asked for an invalid part of the file.
516 .. versionadded:: 0.7
520 description
= "The server cannot provide the requested range."
524 length
: int |
None = None,
525 units
: str = "bytes",
526 description
: str |
None = None,
527 response
: Response |
None = None,
529 """Takes an optional `Content-Range` header value based on ``length``
532 super().__init
__(description
=description
, response
=response
)
538 environ
: WSGIEnvironment |
None = None,
539 scope
: dict |
None = None,
540 ) -> list[tuple[str, str]]:
541 headers
= super().get_headers(environ
, scope
)
542 if self
.length
is not None:
543 headers
.append(("Content-Range", f
"{self.units} */{self.length}"))
547 class ExpectationFailed(HTTPException
):
548 """*417* `Expectation Failed`
550 The server cannot meet the requirements of the Expect request-header.
552 .. versionadded:: 0.7
556 description
= "The server could not meet the requirements of the Expect header"
559 class ImATeapot(HTTPException
):
560 """*418* `I'm a teapot`
562 The server should return this if it is a teapot and someone attempted
563 to brew coffee with it.
565 .. versionadded:: 0.7
569 description
= "This server is a teapot, not a coffee machine"
572 class UnprocessableEntity(HTTPException
):
573 """*422* `Unprocessable Entity`
575 Used if the request is well formed, but the instructions are otherwise
581 "The request was well-formed but was unable to be followed due"
582 " to semantic errors."
586 class Locked(HTTPException
):
589 Used if the resource that is being accessed is locked.
593 description
= "The resource that is being accessed is locked."
596 class FailedDependency(HTTPException
):
597 """*424* `Failed Dependency`
599 Used if the method could not be performed on the resource
600 because the requested action depended on another action and that action failed.
605 "The method could not be performed on the resource because the"
606 " requested action depended on another action and that action"
611 class PreconditionRequired(HTTPException
):
612 """*428* `Precondition Required`
614 The server requires this request to be conditional, typically to prevent
615 the lost update problem, which is a race condition between two or more
616 clients attempting to update a resource through PUT or DELETE. By requiring
617 each client to include a conditional header ("If-Match" or "If-Unmodified-
618 Since") with the proper value retained from a recent GET request, the
619 server ensures that each client has at least seen the previous revision of
625 "This request is required to be conditional; try using"
626 ' "If-Match" or "If-Unmodified-Since".'
630 class _RetryAfter(HTTPException
):
631 """Adds an optional ``retry_after`` parameter which will set the
632 ``Retry-After`` header. May be an :class:`int` number of seconds or
633 a :class:`~datetime.datetime`.
638 description
: str |
None = None,
639 response
: Response |
None = None,
640 retry_after
: datetime |
int |
None = None,
642 super().__init
__(description
, response
)
643 self
.retry_after
= retry_after
647 environ
: WSGIEnvironment |
None = None,
648 scope
: dict |
None = None,
649 ) -> list[tuple[str, str]]:
650 headers
= super().get_headers(environ
, scope
)
653 if isinstance(self
.retry_after
, datetime
):
654 from .http
import http_date
656 value
= http_date(self
.retry_after
)
658 value
= str(self
.retry_after
)
660 headers
.append(("Retry-After", value
))
665 class TooManyRequests(_RetryAfter
):
666 """*429* `Too Many Requests`
668 The server is limiting the rate at which this user receives
669 responses, and this request exceeds that rate. (The server may use
670 any convenient method to identify users and their request rates).
671 The server may include a "Retry-After" header to indicate how long
672 the user should wait before retrying.
674 :param retry_after: If given, set the ``Retry-After`` header to this
675 value. May be an :class:`int` number of seconds or a
676 :class:`~datetime.datetime`.
678 .. versionchanged:: 1.0
679 Added ``retry_after`` parameter.
683 description
= "This user has exceeded an allotted request count. Try again later."
686 class RequestHeaderFieldsTooLarge(HTTPException
):
687 """*431* `Request Header Fields Too Large`
689 The server refuses to process the request because the header fields are too
690 large. One or more individual fields may be too large, or the set of all
691 headers is too large.
695 description
= "One or more header fields exceeds the maximum size."
698 class UnavailableForLegalReasons(HTTPException
):
699 """*451* `Unavailable For Legal Reasons`
701 This status code indicates that the server is denying access to the
702 resource as a consequence of a legal demand.
706 description
= "Unavailable for legal reasons."
709 class InternalServerError(HTTPException
):
710 """*500* `Internal Server Error`
712 Raise if an internal server error occurred. This is a good fallback if an
713 unknown error occurred in the dispatcher.
715 .. versionchanged:: 1.0.0
716 Added the :attr:`original_exception` attribute.
721 "The server encountered an internal error and was unable to"
722 " complete your request. Either the server is overloaded or"
723 " there is an error in the application."
728 description
: str |
None = None,
729 response
: Response |
None = None,
730 original_exception
: BaseException |
None = None,
732 #: The original exception that caused this 500 error. Can be
733 #: used by frameworks to provide context when handling
734 #: unexpected errors.
735 self
.original_exception
= original_exception
736 super().__init
__(description
=description
, response
=response
)
739 class NotImplemented(HTTPException
):
740 """*501* `Not Implemented`
742 Raise if the application does not support the action requested by the
747 description
= "The server does not support the action requested by the browser."
750 class BadGateway(HTTPException
):
751 """*502* `Bad Gateway`
753 If you do proxying in your application you should return this status code
754 if you received an invalid response from the upstream server it accessed
755 in attempting to fulfill the request.
760 "The proxy server received an invalid response from an upstream server."
764 class ServiceUnavailable(_RetryAfter
):
765 """*503* `Service Unavailable`
767 Status code you should return if a service is temporarily
770 :param retry_after: If given, set the ``Retry-After`` header to this
771 value. May be an :class:`int` number of seconds or a
772 :class:`~datetime.datetime`.
774 .. versionchanged:: 1.0
775 Added ``retry_after`` parameter.
780 "The server is temporarily unable to service your request due"
781 " to maintenance downtime or capacity problems. Please try"
786 class GatewayTimeout(HTTPException
):
787 """*504* `Gateway Timeout`
789 Status code you should return if a connection to an upstream server
794 description
= "The connection to an upstream server timed out."
797 class HTTPVersionNotSupported(HTTPException
):
798 """*505* `HTTP Version Not Supported`
800 The server does not support the HTTP protocol version used in the request.
805 "The server does not support the HTTP protocol version used in the request."
809 default_exceptions
: dict[int, type[HTTPException
]] = {}
812 def _find_exceptions() -> None:
813 for obj
in globals().values():
815 is_http_exception
= issubclass(obj
, HTTPException
)
817 is_http_exception
= False
818 if not is_http_exception
or obj
.code
is None:
820 old_obj
= default_exceptions
.get(obj
.code
, None)
821 if old_obj
is not None and issubclass(obj
, old_obj
):
823 default_exceptions
[obj
.code
] = obj
831 """When passed a dict of code -> exception items it can be used as
832 callable that raises exceptions. If the first argument to the
833 callable is an integer it will be looked up in the mapping, if it's
834 a WSGI application it will be raised in a proxy exception.
836 The rest of the arguments are forwarded to the exception constructor.
841 mapping
: dict[int, type[HTTPException
]] |
None = None,
842 extra
: dict[int, type[HTTPException
]] |
None = None,
845 mapping
= default_exceptions
846 self
.mapping
= dict(mapping
)
847 if extra
is not None:
848 self
.mapping
.update(extra
)
851 self
, code
: int | Response
, *args
: t
.Any
, **kwargs
: t
.Any
853 from .sansio
.response
import Response
855 if isinstance(code
, Response
):
856 raise HTTPException(response
=code
)
858 if code
not in self
.mapping
:
859 raise LookupError(f
"no exception for {code!r}")
861 raise self
.mapping
[code
](*args
, **kwargs
)
864 def abort(status
: int | Response
, *args
: t
.Any
, **kwargs
: t
.Any
) -> t
.NoReturn
:
865 """Raises an :py:exc:`HTTPException` for the given status code or WSGI
868 If a status code is given, it will be looked up in the list of
869 exceptions and will raise that exception. If passed a WSGI application,
870 it will wrap it in a proxy WSGI exception and raise that::
872 abort(404) # 404 Not Found
873 abort(Response('Hello World'))
876 _aborter(status
, *args
, **kwargs
)
879 _aborter
: Aborter
= Aborter()