U a p@sBUdZddlZddlZddlZddlmZddlmZddlm Z ej rddl Z ddl mZddl mZdd lmZdd lmZdd lmZGd d d eZGd ddeZGdddeeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZ GdddeZ!Gdd d eZ"Gd!d"d"eZ#Gd#d$d$eZ$Gd%d&d&eZ%Gd'd(d(eZ&Gd)d*d*eZ'Gd+d,d,eZ(Gd-d.d.eZ)Gd/d0d0eZ*Gd1d2d2eZ+Gd3d4d4eZ,Gd5d6d6eZ-Gd7d8d8eZ.Gd9d:d:eZ/Gd;d<dd>eZ1Gd?d@d@eZ2GdAdBdBe2Z3GdCdDdDeZ4GdEdFdFeZ5GdGdHdHeZ6GdIdJdJeZ7GdKdLdLeZ8GdMdNdNe2Z9GdOdPdPeZ:GdQdRdReZ;iZej?efe@dS<ddTdUdVZAeA[AGdWdXdXZBejCe>dYfejDejDdZd[d\d]ZEeBZFeBe@d^<dS)_aImplements a number of Python exceptions which can be raised from within a view to trigger a standard HTTP non-200 response. Usage Example ------------- .. code-block:: python from werkzeug.wrappers.request import Request from werkzeug.exceptions import HTTPException, NotFound def view(request): raise NotFound() @Request.application def application(request): try: return view(request) except HTTPException as e: return e As you can see from this example those exceptions are callable WSGI applications. However, they are not Werkzeug response objects. You can get a response object by calling ``get_response()`` on a HTTP exception. Keep in mind that you may have to pass an environ (WSGI) or scope (ASGI) to ``get_response()`` because some errors fetch additional information relating to the request. 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: .. code-block:: python @Request.application def application(request): try: return view(request) except NotFound as e: return not_found(request) except HTTPException as e: return e N)datetime)escape) _get_environ) StartResponse)WSGIEnvironmentWWWAuthenticateResponsecs^eZdZUdZdZejeed<dZ eje ed<d!eje ejdddfdd Z e d"ej eeje ej dd d d Zee d d dZd#ejdejee dddZd$ejdejee dddZd%ejdejeejeje e fdddZd&ejdejeddddZddejedddZe d ddZe d dd ZZS)' HTTPExceptionzThe base class for all HTTP exceptions. This exception can be called as a WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages. Ncode descriptionr )rresponsereturncs"t|dk r||_||_dSN)super__init__rr)selfrr __class__TC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-1tps7o9u\werkzeug\exceptions.pyrHs zHTTPException.__init__) exceptionnamercsZtjdtddGfddd}tdjd|_|pHjj}||_|_|S)aCreate an exception that is a subclass of the calling HTTP exception and the ``exception`` argument. The first argument to the class will be passed to the wrapped ``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 error description. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Create a subclass manually instead. .. versionchanged:: 0.15.5 The ``show_exception`` attribute controls whether the description includes the wrapped exception message. .. versionchanged:: 0.15.0 The description includes the wrapped exception message. zk'HTTPException.wrap' is deprecated and will be removed in Werkzeug 2.1. Create a subclass manually instead.) stacklevelcsneZdZjZdZd ejejejejddfdd Z e e dfdd Zej e dd d dZZ S) z"HTTPException.wrap..newclsFN)argargskwargsrcs2tj|||dkr"|n ||dSr)rrrrrr)rrrrrus z+HTTPException.wrap..newcls.__init__rcs*|jr$|jdjd|S|jSN : )show_exception _description__name____str__r)rrrrsz.HTTPException.wrap..newcls.descriptionvaluercSs ||_dSrr&rr+rrrrs)N)r' __module__ __qualname__rr&r%tOptionalAnyrpropertystrsetter __classcell__rclsrrrnewclsqs   r9rr') warningswarnDeprecationWarningsys _getframe f_globalsr.r'r/)r8rrr9rr7rwrapRs zHTTPException.wrapr!cCsddlm}||jdS)zThe status name.r)HTTP_STATUS_CODESz Unknown Error)httprAgetr )rrArrrrs zHTTPException.namerenvironscopercCsJ|jdkrd}nt|jts(t|j}n|j}t|dd}d|dS)zGet the description.Nr#z
z

z

)r isinstancer4rreplace)rrErFrrrrget_descriptions   zHTTPException.get_descriptionc Cs2d|jdt|jdt|jd||d S)zGet the HTML body.z?  z

z

r#)r rrrJrrErFrrrget_bodys0zHTTPException.get_bodycCsdgS)zGet a list of headers.)z Content-Typeztext/html; charset=utf-8rrLrrr get_headersszHTTPException.get_headerscCsNddlm}|jdk r|jS|dk r,t|}|||}|||||j|S)ahGet a response object. If one was passed to the exception it's returned directly. :param environ: the optional environ for the request. This can be used to modify the response depending on how the request looked like. :return: a :class:`Response` object or a subclass thereof. rr N)wrappers.responser rrrNrMr )rrErF WSGIResponseheadersrrr get_responses   zHTTPException.get_responser)rEstart_responsercCstd||}|||S)zCall the exception as WSGI application. :param environ: the WSGI environment. :param start_response: the response callable provided by the WSGI server. rP)r0castrR)rrErSrrrr__call__s zHTTPException.__call__cCs,|jdk r|jnd}|d|jd|jS)N???rKr$)r rrrr rrrr(szHTTPException.__str__cCs4|jdk r|jnd}dt|jd|d|jdS)NrV)r typer'rrWrrr__repr__szHTTPException.__repr__)NN)N)NN)NN)NN)NN)r'r.r/__doc__r r0r1int__annotations__rr4r classmethodType BaseExceptionr@r3rdictrJrMListTuplerNrRIterablebytesrUr(rZr6rrrrr ?sj  ?     r c@seZdZdZdZdZdS) BadRequestz*400* `Bad Request` Raise if the browser sends something to the application the application or server cannot handle. izLThe browser (or proxy) sent a request that this server could not understand.Nr'r.r/r[r rrrrrrfsrfcsheZdZdZejZdZd ej e ej ej dfdd Z e e ddd Zeje dd d d ZZS) BadRequestKeyErrorzAn exception that is used to signal both a :exc:`KeyError` and a :exc:`BadRequest`. Used by many of the datastructures. FN)rrrcs2tj|||dkr"t|n t||dSr)rrKeyErrorr rrrrs zBadRequestKeyError.__init__r!cCs*|jr$|jdtjdt|S|jSr")r%r&rir'r(r)rrrr szBadRequestKeyError.descriptionr*cCs ||_dSrr,r-rrrrs)N)r'r.r/r[rfrr&r%r0r1r4r2rr3r5r6rrrrrhs" rhc@seZdZdZdS)ClientDisconnecteda)Internal exception that is raised if Werkzeug detects a disconnected client. Since the client is already gone at that point attempting to send the error message to the client might not work and might ultimately result in another exception in the server. Mainly this is here so that it is silenced by default as far as Werkzeug is concerned. Since disconnections cannot be reliably detected and are unspecified by WSGI to a large extent this might or might not be raised if a client is gone. .. versionadded:: 0.8 Nr'r.r/r[rrrrrjsrjc@seZdZdZdS) SecurityErrorzRaised if something triggers a security error. This is otherwise exactly like a bad request error. .. versionadded:: 0.9 Nrkrrrrrl(srlc@seZdZdZdS)BadHostzSRaised if the submitted host is badly formatted. .. versionadded:: 0.11.2 Nrkrrrrrm0srmcseZdZdZdZdZdejeejdejej dej dfddfdd Z dejd eje ej ejeefd fd d ZZS) Unauthorizedaz*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 and other schemes. Use :class:`~werkzeug.datastructures.WWWAuthenticate` to create correctly formatted values. Strictly speaking a 401 response is invalid if it doesn't provide at least one value for this header, although real clients typically don't care. :param description: Override the default message used for the body of the response. :param www-authenticate: A single value, or list of values, for the WWW-Authenticate header(s). .. versionchanged:: 2.0 Serialize multiple ``www_authenticate`` items into multiple ``WWW-Authenticate`` headers, rather than joining them into a single value, for better interoperability. .. versionchanged:: 0.15.3 If the ``www_authenticate`` argument is not set, the ``WWW-Authenticate`` header is not set. .. versionchanged:: 0.15.3 The ``response`` argument was restored. .. versionchanged:: 0.15.1 ``description`` was moved back as the first argument, restoring its previous position. .. versionchanged:: 0.15.0 ``www_authenticate`` was added as the first argument, ahead of ``description``. izThe 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.Nr r )rrwww_authenticatercs4t||ddlm}t||r*|f}||_dS)Nrr)rrdatastructuresr rHro)rrrror rrrres   zUnauthorized.__init__rrDcs.t||}|jr*|dd|jD|S)Ncss|]}dt|fVqdS)zWWW-AuthenticateN)r4).0xrrr }sz+Unauthorized.get_headers..)rrNroextendrrErFrQrrrrNvszUnauthorized.get_headers)NNN)NN)r'r.r/r[r rr0r1r4UnionrdrrarbrcrNr6rrrrrn7s,% rnc@seZdZdZdZdZdS) Forbiddenz*403* `Forbidden` Raise if the user doesn't have the permission for the requested resource but was authenticated. izzYou don't have the permission to access the requested resource. It is either read-protected or not readable by the server.Nrgrrrrrwsrwc@seZdZdZdZdZdS)NotFoundzQ*404* `Not Found` Raise if a resource does not exist and never existed. izxThe requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.NrgrrrrrxsrxcseZdZdZdZdZd ejeje eje ejdddfdd Z dejd eje ej ej e e fd fd d ZZS)MethodNotAlloweda*405* `Method Not Allowed` Raise if the server used a method the resource does not handle. For example `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 valid methods in the header which you can do with that list. iz0The method is not allowed for the requested URL.Nr ) valid_methodsrrrcstj||d||_dS)zkTakes an optional list of valid http methods starting with werkzeug 0.3 the list will be mandatory.rrN)rrrz)rrzrrrrrrszMethodNotAllowed.__init__rrDcs.t||}|jr*|dd|jf|S)NZAllowz, )rrNrzappendjoinrurrrrNszMethodNotAllowed.get_headers)NNN)NN)r'r.r/r[r rr0r1rdr4rrarbrcrNr6rrrrrys&  ryc@seZdZdZdZdZdS) NotAcceptablez*406* `Not Acceptable` Raise if the server can't return any content conforming to the `Accept` headers of the client. izThe 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.Nrgrrrrr~sr~c@seZdZdZdZdZdS)RequestTimeoutz?*408* `Request Timeout` Raise to signalize a timeout. izqThe server closed the network connection because the browser didn't finish the request within the specified time.Nrgrrrrrsrc@seZdZdZdZdZdS)Conflictz*409* `Conflict` Raise to signal that a request cannot be completed because it conflicts with the current state on the server. .. versionadded:: 0.7 iz~A conflict happened while processing the request. The resource might have been modified while the request was being processed.Nrgrrrrrsrc@seZdZdZdZdZdS)Goneza*410* `Gone` Raise if a resource existed previously and went away without new location. izThe 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.Nrgrrrrrsrc@seZdZdZdZdZdS)LengthRequiredz*411* `Length Required` Raise if the browser submitted data but no ``Content-Length`` header which is required for the kind of processing the server does. izOA request with this method requires a valid Content-Length header.Nrgrrrrrsrc@seZdZdZdZdZdS)PreconditionFailedz*412* `Precondition Failed` Status code used in combination with ``If-Match``, ``If-None-Match``, or ``If-Unmodified-Since``. izGThe precondition on the request for the URL failed positive evaluation.Nrgrrrrr src@seZdZdZdZdZdS)RequestEntityTooLargez~*413* `Request Entity Too Large` The status code one should return if the data submitted exceeded a given limit. iz6The data value transmitted exceeds the capacity limit.Nrgrrrrrsrc@seZdZdZdZdZdS)RequestURITooLargezI*414* `Request URI Too Large` Like *413* but for too long URLs. izlThe length of the requested URL exceeds the capacity limit for this server. The request cannot be processed.Nrgrrrrr#src@seZdZdZdZdZdS)UnsupportedMediaTypez*415* `Unsupported Media Type` The status code returned if the server is unable to handle the media type the client transmitted. izFThe server does not support the media type transmitted in the request.Nrgrrrrr0srcs~eZdZdZdZdZdejee eje ejdddfdd Z dejd eje ej ej e e fd fd d ZZS)RequestedRangeNotSatisfiablez~*416* `Requested Range Not Satisfiable` The client asked for an invalid part of the file. .. versionadded:: 0.7 iz.The server cannot provide the requested range.Nrer )lengthunitsrrrcs tj||d||_||_dS)z^Takes an optional `Content-Range` header value based on ``length`` parameter. r{N)rrrr)rrrrrrrrrHs z%RequestedRangeNotSatisfiable.__init__rrDcs8t||}|jdk r4|d|jd|jf|S)Nz Content-Rangez */)rrNrr|rrurrrrNVs z(RequestedRangeNotSatisfiable.get_headers)NreNN)NN)r'r.r/r[r rr0r1r\r4rrarbrcrNr6rrrrr=s*rc@seZdZdZdZdZdS)ExpectationFailedz*417* `Expectation Failed` The server cannot meet the requirements of the Expect request-header. .. versionadded:: 0.7 iz?The server could not meet the requirements of the Expect headerNrgrrrrrasrc@seZdZdZdZdZdS) ImATeapotz*418* `I'm a teapot` The server should return this if it is a teapot and someone attempted to brew coffee with it. .. versionadded:: 0.7 iz-This server is a teapot, not a coffee machineNrgrrrrrmsrc@seZdZdZdZdZdS)UnprocessableEntityz|*422* `Unprocessable Entity` Used if the request is well formed, but the instructions are otherwise incorrect. izQThe request was well-formed but was unable to be followed due to semantic errors.Nrgrrrrrzsrc@seZdZdZdZdZdS)LockedzO*423* `Locked` Used if the resource that is being accessed is locked. iz.The resource that is being accessed is locked.Nrgrrrrrsrc@seZdZdZdZdZdS)FailedDependencyz*424* `Failed Dependency` Used if the method could not be performed on the resource because the requested action depended on another action and that action failed. izThe method could not be performed on the resource because the requested action depended on another action and that action failed.Nrgrrrrrsrc@seZdZdZdZdZdS)PreconditionRequireda*428* `Precondition Required` The server requires this request to be conditional, typically to prevent the lost update problem, which is a race condition between two or more clients attempting to update a resource through PUT or DELETE. By requiring each client to include a conditional header ("If-Match" or "If-Unmodified- Since") with the proper value retained from a recent GET request, the server ensures that each client has at least seen the previous revision of the resource. izZThis request is required to be conditional; try using "If-Match" or "If-Unmodified-Since".Nrgrrrrrs rcs~eZdZdZd ejeejdejejee fddfdd Z d ejdeje ej ej eefdfd d ZZS) _RetryAfterzAdds an optional ``retry_after`` parameter which will set the ``Retry-After`` header. May be an :class:`int` number of seconds or a :class:`~datetime.datetime`. Nr )rr retry_afterrcst||||_dSr)rrr)rrrrrrrrsz_RetryAfter.__init__rrDcsTt||}|jrPt|jtr8ddlm}||j}n t|j}|d|f|S)Nr) http_datez Retry-After) rrNrrHrrBrr4r|)rrErFrQrr+rrrrNs    z_RetryAfter.get_headers)NNN)NN)r'r.r/r[r0r1r4rvrr\rrarbrcrNr6rrrrrs" rc@seZdZdZdZdZdS)TooManyRequestsaO*429* `Too Many Requests` The server is limiting the rate at which this user receives responses, and this request exceeds that rate. (The server may use any convenient method to identify users and their request rates). The server may include a "Retry-After" header to indicate how long the user should wait before retrying. :param retry_after: If given, set the ``Retry-After`` header to this value. May be an :class:`int` number of seconds or a :class:`~datetime.datetime`. .. versionchanged:: 1.0 Added ``retry_after`` parameter. izBThis user has exceeded an allotted request count. Try again later.Nrgrrrrrsrc@seZdZdZdZdZdS)RequestHeaderFieldsTooLargez*431* `Request Header Fields Too Large` The server refuses to process the request because the header fields are too large. One or more individual fields may be too large, or the set of all headers is too large. iz3One or more header fields exceeds the maximum size.Nrgrrrrrsrc@seZdZdZdZdZdS)UnavailableForLegalReasonsz*451* `Unavailable For Legal Reasons` This status code indicates that the server is denying access to the resource as a consequence of a legal demand. izUnavailable for legal reasons.NrgrrrrrsrcsHeZdZdZdZdZd ejeejdeje ddfdd Z Z S) InternalServerErrorz*500* `Internal Server Error` Raise if an internal server error occurred. This is a good fallback if an unknown error occurred in the dispatcher. .. versionchanged:: 1.0.0 Added the :attr:`original_exception` attribute. izThe 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.Nr )rroriginal_exceptionrcs||_tj||ddS)Nr{)rrr)rrrrrrrrs zInternalServerError.__init__)NNN) r'r.r/r[r rr0r1r4r`rr6rrrrrs rc@seZdZdZdZdZdS)NotImplementedzt*501* `Not Implemented` Raise if the application does not support the action requested by the browser. iz@The server does not support the action requested by the browser.Nrgrrrrr!src@seZdZdZdZdZdS) BadGatewayz*502* `Bad Gateway` If you do proxying in your application you should return this status code if you received an invalid response from the upstream server it accessed in attempting to fulfill the request. izFThe proxy server received an invalid response from an upstream server.Nrgrrrrr,src@seZdZdZdZdZdS)ServiceUnavailableab*503* `Service Unavailable` Status code you should return if a service is temporarily unavailable. :param retry_after: If given, set the ``Retry-After`` header to this value. May be an :class:`int` number of seconds or a :class:`~datetime.datetime`. .. versionchanged:: 1.0 Added ``retry_after`` parameter. izThe server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.Nrgrrrrr:s rc@seZdZdZdZdZdS)GatewayTimeoutzt*504* `Gateway Timeout` Status code you should return if a connection to an upstream server times out. iz/The connection to an upstream server timed out.NrgrrrrrPsrc@seZdZdZdZdZdS)HTTPVersionNotSupportedzw*505* `HTTP Version Not Supported` The server does not support the HTTP protocol version used in the request. izJThe server does not support the HTTP protocol version used in the request.Nrgrrrrr[srdefault_exceptionsr!c CsxtD]h}zt|t}Wntk r4d}YnX|r |jdkrFq t|jd}|dk rht||rhq |t|j<q dS)NF)globalsvalues issubclassr TypeErrorr rrC)objZis_http_exceptionZold_objrrr_find_exceptionsjs rc@sreZdZdZd ejejeeje fejejeeje fddddZ ej edfej ej ddd d Z dS) AborteraYWhen passed a dict of code -> exception items it can be used as callable that raises exceptions. If the first argument to the callable is an integer it will be looked up in the mapping, if it's a WSGI application it will be raised in a proxy exception. The rest of the arguments are forwarded to the exception constructor. N)mappingextrarcCs.|dkr t}t||_|dk r*|j|dSr)rrarupdate)rrrrrrrs  zAborter.__init__r te.NoReturn)r rrrcOsLddlm}t||r t|d||jkr8td||j|||dS)Nrr )rzno exception for )sansio.responser rHr r LookupError)rr rrr rrrrUs     zAborter.__call__)NN)r'r.r/r[r0r1Dictr\r_r rrvr2rUrrrrr|s  rr r)statusrrrcOst|f||dS)atRaises an :py:exc:`HTTPException` for the given status code or WSGI application. If a status code is given, it will be looked up in the list of exceptions 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 Found abort(Response('Hello World')) N)_aborter)rrrrrrabortsrr)Gr[r=typingr0r:rhtmlr _internalr TYPE_CHECKINGZtyping_extensionsteZ_typeshed.wsgirrrpr rr rOrP Exceptionr rfrirhrjrlrmrnrwrxryr~rrrrrrrrrrrrrrrrrrrrrrrrrrrr\r_r]rrrvr2rrrrrrsz-        +"J $     $   #     #