# -*- coding: utf-8 -*-"""werkzeug.exceptions~~~~~~~~~~~~~~~~~~~This module implements a number of Python exceptions you can raise fromwithin your views to trigger a standard non-200 response.Usage Example-------------::from werkzeug.wrappers import BaseRequestfrom werkzeug.wsgi import responderfrom werkzeug.exceptions import HTTPException, NotFounddef view(request):raise NotFound()@responderdef application(environ, start_response):request = BaseRequest(environ)try:return view(request)except HTTPException as e:return eAs 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::@responderdef application(environ, start_response):request = BaseRequest(environ)try:return view(request)except NotFound, e:return not_found(request)except HTTPException, e:return e:copyright: 2007 Pallets:license: BSD-3-Clause"""import sysfrom datetime import datetimefrom ._compat import implements_to_stringfrom ._compat import integer_typesfrom ._compat import iteritemsfrom ._compat import text_typefrom ._internal import _get_environfrom .utils import escape@implements_to_stringclass HTTPException(Exception):"""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."""code = Nonedescription = Nonedef __init__(self, description=None, response=None):super(HTTPException, self).__init__()if description is not None:self.description = descriptionself.response = response@classmethoddef wrap(cls, exception, name=None):"""Create an exception that is a subclass of the calling HTTPexception and the ``exception`` argument.The first argument to the class will be passed to thewrapped ``exception``, the rest to the HTTP exception. If``e.args`` is not empty and ``e.show_exception`` is ``True``,the wrapped exception message is added to the HTTP errordescription... versionchanged:: 0.15.5The ``show_exception`` attribute controls whether thedescription includes the wrapped exception message... versionchanged:: 0.15.0The description includes the wrapped exception message."""class newcls(cls, exception):_description = cls.descriptionshow_exception = Falsedef __init__(self, arg=None, *args, **kwargs):super(cls, self).__init__(*args, **kwargs)if arg is None:exception.__init__(self)else:exception.__init__(self, arg)@propertydef description(self):if self.show_exception:return "{}\n{}: {}".format(self._description, exception.__name__, exception.__str__(self))return self._description@description.setterdef description(self, value):self._description = valuenewcls.__module__ = sys._getframe(1).f_globals.get("__name__")name = name or cls.__name__ + exception.__name__newcls.__name__ = newcls.__qualname__ = namereturn newcls@propertydef name(self):"""The status name."""from .http import HTTP_STATUS_CODESreturn HTTP_STATUS_CODES.get(self.code, "Unknown Error")def get_description(self, environ=None):"""Get the description."""return u"<p>%s</p>" % escape(self.description).replace("\n", "<br>")def get_body(self, environ=None):"""Get the HTML body."""return text_type((u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'u"<title>%(code)s %(name)s</title>\n"u"<h1>%(name)s</h1>\n"u"%(description)s\n")% {"code": self.code,"name": escape(self.name),"description": self.get_description(environ),})def get_headers(self, environ=None):"""Get a list of headers."""return [("Content-Type", "text/html; charset=utf-8")]def get_response(self, environ=None):"""Get a response object. If one was passed to the exceptionit's returned directly.:param environ: the optional environ for the request. Thiscan be used to modify the response dependingon how the request looked like.:return: a :class:`Response` object or a subclass thereof."""from .wrappers.response import Responseif self.response is not None:return self.responseif environ is not None:environ = _get_environ(environ)headers = self.get_headers(environ)return Response(self.get_body(environ), self.code, headers)def __call__(self, environ, start_response):"""Call the exception as WSGI application.:param environ: the WSGI environment.:param start_response: the response callable provided by the WSGIserver."""response = self.get_response(environ)return response(environ, start_response)def __str__(self):code = self.code if self.code is not None else "???"return "%s %s: %s" % (code, self.name, self.description)def __repr__(self):code = self.code if self.code is not None else "???"return "<%s '%s: %s'>" % (self.__class__.__name__, code, self.name)class BadRequest(HTTPException):"""*400* `Bad Request`Raise if the browser sends something to the application the applicationor server cannot handle."""code = 400description = ("The browser (or proxy) sent a request that this server could ""not understand.")class ClientDisconnected(BadRequest):"""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 extent this might or might not be raised if a clientis gone... versionadded:: 0.8"""class SecurityError(BadRequest):"""Raised if something triggers a security error. This is otherwiseexactly like a bad request error... versionadded:: 0.9"""class BadHost(BadRequest):"""Raised if the submitted host is badly formatted... versionadded:: 0.11.2"""class Unauthorized(HTTPException):"""*401* ``Unauthorized``Raise if the user is not authorized to access a resource.The ``www_authenticate`` argument should be used to set the``WWW-Authenticate`` header. This is used for HTTP basic auth andother schemes. Use :class:`~werkzeug.datastructures.WWWAuthenticate`to create correctly formatted values. Strictly speaking a 401response is invalid if it doesn't provide at least one value forthis header, although real clients typically don't care.:param description: Override the default message used for the bodyof the response.:param www-authenticate: A single value, or list of values, for theWWW-Authenticate header... versionchanged:: 0.15.3If the ``www_authenticate`` argument is not set, the``WWW-Authenticate`` header is not set... versionchanged:: 0.15.3The ``response`` argument was restored... versionchanged:: 0.15.1``description`` was moved back as the first argument, restoringits previous position... versionchanged:: 0.15.0``www_authenticate`` was added as the first argument, ahead of``description``."""code = 401description = ("The server could not verify that you are authorized to access"" the URL requested. You either supplied the wrong credentials"" (e.g. a bad password), or your browser doesn't understand"" how to supply the credentials required.")def __init__(self, description=None, response=None, www_authenticate=None):HTTPException.__init__(self, description, response)if www_authenticate is not None:if not isinstance(www_authenticate, (tuple, list)):www_authenticate = (www_authenticate,)self.www_authenticate = www_authenticatedef get_headers(self, environ=None):headers = HTTPException.get_headers(self, environ)if self.www_authenticate:headers.append(("WWW-Authenticate", ", ".join([str(x) for x in self.www_authenticate])))return headersclass Forbidden(HTTPException):"""*403* `Forbidden`Raise if the user doesn't have the permission for the requested resourcebut was authenticated."""code = 403description = ("You don't have the permission to access the requested"" resource. It is either read-protected or not readable by the"" server.")class NotFound(HTTPException):"""*404* `Not Found`Raise if a resource does not exist and never existed."""code = 404description = ("The requested URL was not found on the server. If you entered"" the URL manually please check your spelling and try again.")class MethodNotAllowed(HTTPException):"""*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."""code = 405description = "The method is not allowed for the requested URL."def __init__(self, valid_methods=None, description=None):"""Takes an optional list of valid http methodsstarting with werkzeug 0.3 the list will be mandatory."""HTTPException.__init__(self, description)self.valid_methods = valid_methodsdef get_headers(self, environ=None):headers = HTTPException.get_headers(self, environ)if self.valid_methods:headers.append(("Allow", ", ".join(self.valid_methods)))return headersclass NotAcceptable(HTTPException):"""*406* `Not Acceptable`Raise if the server can't return any content conforming to the`Accept` headers of the client."""code = 406description = ("The resource identified by the request is only capable of"" generating response entities which have content"" characteristics not acceptable according to the accept"" headers sent in the request.")class RequestTimeout(HTTPException):"""*408* `Request Timeout`Raise to signalize a timeout."""code = 408description = ("The server closed the network connection because the browser"" didn't finish the request within the specified time.")class Conflict(HTTPException):"""*409* `Conflict`Raise to signal that a request cannot be completed because it conflictswith the current state on the server... versionadded:: 0.7"""code = 409description = ("A conflict happened while processing the request. The"" resource might have been modified while the request was being"" processed.")class Gone(HTTPException):"""*410* `Gone`Raise if a resource existed previously and went away without new location."""code = 410description = ("The requested URL is no longer available on this server and"" there is no forwarding address. If you followed a link from a"" foreign page, please contact the author of this page.")class LengthRequired(HTTPException):"""*411* `Length Required`Raise if the browser submitted data but no ``Content-Length`` header whichis required for the kind of processing the server does."""code = 411description = ("A request with this method requires a valid <code>Content-""Length</code> header.")class PreconditionFailed(HTTPException):"""*412* `Precondition Failed`Status code used in combination with ``If-Match``, ``If-None-Match``, or``If-Unmodified-Since``."""code = 412description = ("The precondition on the request for the URL failed positive evaluation.")class RequestEntityTooLarge(HTTPException):"""*413* `Request Entity Too Large`The status code one should return if the data submitted exceeded a givenlimit."""code = 413description = "The data value transmitted exceeds the capacity limit."class RequestURITooLarge(HTTPException):"""*414* `Request URI Too Large`Like *413* but for too long URLs."""code = 414description = ("The length of the requested URL exceeds the capacity limit for"" this server. The request cannot be processed.")class UnsupportedMediaType(HTTPException):"""*415* `Unsupported Media Type`The status code returned if the server is unable to handle the media typethe client transmitted."""code = 415description = ("The server does not support the media type transmitted in the request.")class RequestedRangeNotSatisfiable(HTTPException):"""*416* `Requested Range Not Satisfiable`The client asked for an invalid part of the file... versionadded:: 0.7"""code = 416description = "The server cannot provide the requested range."def __init__(self, length=None, units="bytes", description=None):"""Takes an optional `Content-Range` header value based on ``length``parameter."""HTTPException.__init__(self, description)self.length = lengthself.units = unitsdef get_headers(self, environ=None):headers = HTTPException.get_headers(self, environ)if self.length is not None:headers.append(("Content-Range", "%s */%d" % (self.units, self.length)))return headersclass ExpectationFailed(HTTPException):"""*417* `Expectation Failed`The server cannot meet the requirements of the Expect request-header... versionadded:: 0.7"""code = 417description = "The server could not meet the requirements of the Expect header"class ImATeapot(HTTPException):"""*418* `I'm a teapot`The server should return this if it is a teapot and someone attemptedto brew coffee with it... versionadded:: 0.7"""code = 418description = "This server is a teapot, not a coffee machine"class UnprocessableEntity(HTTPException):"""*422* `Unprocessable Entity`Used if the request is well formed, but the instructions are otherwiseincorrect."""code = 422description = ("The request was well-formed but was unable to be followed due"" to semantic errors.")class Locked(HTTPException):"""*423* `Locked`Used if the resource that is being accessed is locked."""code = 423description = "The resource that is being accessed is locked."class FailedDependency(HTTPException):"""*424* `Failed Dependency`Used if the method could not be performed on the resourcebecause the requested action depended on another action and that action failed."""code = 424description = ("The method could not be performed on the resource because the"" requested action depended on another action and that action"" failed.")class PreconditionRequired(HTTPException):"""*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."""code = 428description = ("This request is required to be conditional; try using"' "If-Match" or "If-Unmodified-Since".')class _RetryAfter(HTTPException):"""Adds an optional ``retry_after`` parameter which will set the``Retry-After`` header. May be an :class:`int` number of seconds ora :class:`~datetime.datetime`."""def __init__(self, description=None, response=None, retry_after=None):super(_RetryAfter, self).__init__(description, response)self.retry_after = retry_afterdef get_headers(self, environ=None):headers = super(_RetryAfter, self).get_headers(environ)if self.retry_after:if isinstance(self.retry_after, datetime):from .http import http_datevalue = http_date(self.retry_after)else:value = str(self.retry_after)headers.append(("Retry-After", value))return headersclass TooManyRequests(_RetryAfter):"""*429* `Too Many Requests`The server is limiting the rate at which this user receivesresponses, and this request exceeds that rate. (The server may useany convenient method to identify users and their request rates).The server may include a "Retry-After" header to indicate how longthe user should wait before retrying.:param retry_after: If given, set the ``Retry-After`` header to thisvalue. May be an :class:`int` number of seconds or a:class:`~datetime.datetime`... versionchanged:: 1.0Added ``retry_after`` parameter."""code = 429description = "This user has exceeded an allotted request count. Try again later."class RequestHeaderFieldsTooLarge(HTTPException):"""*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."""code = 431description = "One or more header fields exceeds the maximum size."class UnavailableForLegalReasons(HTTPException):"""*451* `Unavailable For Legal Reasons`This status code indicates that the server is denying access to theresource as a consequence of a legal demand."""code = 451description = "Unavailable for legal reasons."class InternalServerError(HTTPException):"""*500* `Internal Server Error`Raise if an internal server error occurred. This is a good fallback if anunknown error occurred in the dispatcher... versionchanged:: 1.0.0Added the :attr:`original_exception` attribute."""code = 500description = ("The server encountered an internal error and was unable to"" complete your request. Either the server is overloaded or"" there is an error in the application.")def __init__(self, description=None, response=None, original_exception=None):#: The original exception that caused this 500 error. Can be#: used by frameworks to provide context when handling#: unexpected errors.self.original_exception = original_exceptionsuper(InternalServerError, self).__init__(description=description, response=response)class NotImplemented(HTTPException):"""*501* `Not Implemented`Raise if the application does not support the action requested by thebrowser."""code = 501description = "The server does not support the action requested by the browser."class BadGateway(HTTPException):"""*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."""code = 502description = ("The proxy server received an invalid response from an upstream server.")class ServiceUnavailable(_RetryAfter):"""*503* `Service Unavailable`Status code you should return if a service is temporarilyunavailable.:param retry_after: If given, set the ``Retry-After`` header to thisvalue. May be an :class:`int` number of seconds or a:class:`~datetime.datetime`... versionchanged:: 1.0Added ``retry_after`` parameter."""code = 503description = ("The server is temporarily unable to service your request due"" to maintenance downtime or capacity problems. Please try"" again later.")class GatewayTimeout(HTTPException):"""*504* `Gateway Timeout`Status code you should return if a connection to an upstream servertimes out."""code = 504description = "The connection to an upstream server timed out."class HTTPVersionNotSupported(HTTPException):"""*505* `HTTP Version Not Supported`The server does not support the HTTP protocol version used in the request."""code = 505description = ("The server does not support the HTTP protocol version used in the request.")default_exceptions = {}__all__ = ["HTTPException"]def _find_exceptions():for _name, obj in iteritems(globals()):try:is_http_exception = issubclass(obj, HTTPException)except TypeError:is_http_exception = Falseif not is_http_exception or obj.code is None:continue__all__.append(obj.__name__)old_obj = default_exceptions.get(obj.code, None)if old_obj is not None and issubclass(obj, old_obj):continuedefault_exceptions[obj.code] = obj_find_exceptions()del _find_exceptionsclass Aborter(object):"""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."""def __init__(self, mapping=None, extra=None):if mapping is None:mapping = default_exceptionsself.mapping = dict(mapping)if extra is not None:self.mapping.update(extra)def __call__(self, code, *args, **kwargs):if not args and not kwargs and not isinstance(code, integer_types):raise HTTPException(response=code)if code not in self.mapping:raise LookupError("no exception for %r" % code)raise self.mapping[code](*args, **kwargs)def abort(status, *args, **kwargs):"""Raises an :py:exc:`HTTPException` for the given status code or WSGIapplication.If a status code is given, it will be looked up in the list ofexceptions and will raise that exception. If passed a WSGI application,it will wrap it in a proxy WSGI exception and raise that::abort(404) # 404 Not Foundabort(Response('Hello World'))"""return _aborter(status, *args, **kwargs)_aborter = Aborter()#: An exception that is used to signal both a :exc:`KeyError` and a#: :exc:`BadRequest`. Used by many of the datastructures.BadRequestKeyError = BadRequest.wrap(KeyError)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。