4V=jT\ddlmZddlZddlZddlmZddlmZddlm Z ddlm Z ddl m Z dd lmZejr dd lmZdd lmZd5dZ d6d7dZd8dZ d9d:dZd;d Z dd&ZGd'd(Z d?d@d.ZGd/d0ZGd1d2ZGd3d4ejZ dS)A) annotationsN)partialupdate_wrapper)ClientDisconnected)RequestEntityTooLarge)utils)host_is_trusted)WSGIApplication)WSGIEnvironmentf t.Callable[..., WSGIApplication]returnr c*tfdS)a Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example:: @responder def application(environ, start_response): return Response('Hello World!') c$||ddS)N)ars ;C:\PYTHON\_runtimes\venv\Lib\site-packages\werkzeug/wsgi.pyzresponder..sUQQUAbccF^r)rs`r responderrs 3333Q 7 77rFenvironr root_onlyboolstrip_querystring host_only trusted_hostst.Collection[str] | Nonestrc|dt||d}|sb|dd|d<|sG|dd|d<|s,|ddd |d <tjd i|S) aXRecreate the URL for a request from the parts in a WSGI environment. The URL is an IRI, not a URI, so it may contain Unicode characters. Use :func:`~werkzeug.urls.iri_to_uri` to convert it to ASCII. :param environ: The WSGI environment to get the URL parts from. :param root_only: Only build the root path, don't include the remaining path or query string. :param strip_querystring: Don't include the query string. :param host_only: Only build the scheme and host. :param trusted_hosts: A list of trusted host names to validate the host against. wsgi.url_scheme)schemehost SCRIPT_NAME root_path PATH_INFOpath QUERY_STRINGlatin1 query_stringr)get_hostgetencode _sansio_utilsget_current_url)rrrrrpartss rr2r2s,+,-00  E Y$[[;;k Y#KK R88E&M$ Y(/ NB(G(G(N(Nx(X(Xn%  ( 1 15 1 11rtuple[str, int | None] | Nonec|d}|dS t|dd}n#ttf$rd}YnwxYw||fS)N SERVER_NAME SERVER_PORT)r/int TypeError ValueError)rnameports r _get_serverr=Esv ;;} % %D |tw{{=$??@@ z " :s#?AAc|tj|d|dt||S)abGet and validate a request's ``host:port`` based on the values in the given WSGI environ. The ``Host`` header sent by the client is preferred. Otherwise, the server's configured address is used. If the server address is a Unix socket, it is ignored. The port is omitted if it matches the standard HTTP or HTTPS ports. The value is passed through :func:`host_is_trusted`. The host must be made up of valid characters, but this does not check validity beyond that. If a list of trusted domains is given, the domain must match one. :param environ: The WSGI environ. :param trusted_hosts: A list of trusted domains to match. These should already be IDNA encoded, but will be encoded if needed. The port is ignored for this check. If a name starts with a dot it will match as a suffix, accepting all subdomains. If empty or ``None``, all domains are allowed. :return: Host, with port if necessary. :raise .SecurityError: If the host is not trusted. .. versionchanged:: 3.2 The characters of the host value are validated. The empty string is no longer allowed if no header value is available. .. versionchanged:: 3.2 When using the server address, Unix sockets are ignored. .. versionchanged:: 3.1.3 If ``SERVER_NAME`` is IPv6, it is wrapped in ``[]``. r# HTTP_HOST)r1r.r/r=)rrs rr.r.Vs@D  !!" K  G   r int | Nonecztj|d|dS)adReturn the ``Content-Length`` header value as an int. If the header is not given or the ``Transfer-Encoding`` header is ``chunked``, ``None`` is returned to indicate a streaming request. If the value is not an integer, or negative, 0 is returned. :param environ: The WSGI environ to get the content length from. .. versionadded:: 0.9 CONTENT_LENGTHHTTP_TRANSFER_ENCODING)http_content_lengthhttp_transfer_encoding)r1get_content_lengthr/)rs rrFrFs>  +#KK(899&{{+CDD   rT safe_fallbackmax_content_length t.IO[bytes]ctjtjt|d}t |}||||krt d|vr>|:tjtjtt ||dS|S||rtjn|Stjtjtt ||S)aReturn the WSGI input stream, wrapped so that it may be read safely without going past the ``Content-Length`` header value or ``max_content_length``. If ``Content-Length`` exceeds ``max_content_length``, a :exc:`RequestEntityTooLarge`` ``413 Content Too Large`` error is raised. If the WSGI server sets ``environ["wsgi.input_terminated"]``, it indicates that the server handles terminating the stream, so it is safe to read directly. For example, a server that knows how to handle chunked requests safely would set this. If ``max_content_length`` is set, it can be enforced on streams if ``wsgi.input_terminated`` is set. Otherwise, an empty stream is returned unless the user explicitly disables this safe fallback. If the limit is reached before the underlying stream is exhausted (such as a file that is too large, or an infinite stream), the remaining contents of the stream cannot be read safely. Depending on how the server handles this, clients may show a "connection reset" failure instead of seeing the 413 response. :param environ: The WSGI environ containing the stream. :param safe_fallback: Return an empty stream when ``Content-Length`` is not set. Disabling this allows infinite streams, which can be a denial-of-service risk. :param max_content_length: The maximum length that content-length or streaming requests may not exceed. .. versionchanged:: 2.3.2 ``max_content_length`` is only applied to streaming requests if the server sets ``wsgi.input_terminated``. .. versionchanged:: 2.3 Check ``max_content_length`` and raise an error if it is exceeded. .. versionadded:: 0.9 z wsgi.inputNzwsgi.input_terminatedT)is_max) tcastIObytesrFr LimitedStreamioBytesIO)rrGrHstreamcontent_lengths rget_input_streamrUsNVADK!6 7 7F'00N!&8&D . . .')) )'))  )6U ]63EdSSS  ,8rz|||&8 6!$u+}V^DD E EErc|ddd}|dS)zReturn ``PATH_INFO`` from the WSGI environment. :param environ: WSGI environment to get the path from. .. versionchanged:: 3.0 The ``charset`` and ``errors`` parameters were removed. .. versionadded:: 0.9 r)r'r,replace)errors)r/r0decode)rr*s r get_path_inforZs9++k2..55h??D ;;i; ( ((rc6eZdZdZ ddd Zdd Zdd Zdd ZdS)ClosingIteratoraAThe WSGI specification requires that all middlewares and gateways respect the `close` callback of the iterable returned by the application. Because it is useful to add another close action to a returned iterable and adding a custom iterable is a boring task this class can be used for that:: return ClosingIterator(app(environ, start_response), [cleanup_session, cleanup_locals]) If there is just one close function it can be passed instead of the list. A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started:: try: return response(environ, start_response) finally: cleanup_session() cleanup_locals() Niterablet.Iterable[bytes] callbacks@None | (t.Callable[[], None] | t.Iterable[t.Callable[[], None]])rNonecZt|}tjtjgtft t ||_|g}n"t|r|g}nt|}t|dd}|r| d|||_ dS)Ncloser) iterrLrMCallablerOrnext_nextcallablelistgetattrinsert _callbacks)selfr]r_iteratoriterable_closes r__init__zClosingIterator.__init__s >>VAJr5y1743J3JKK  II i  (" IIYI 7D99  0   Q / / /#rc|SNrrms r__iter__zClosingIterator.__iter__  rrOc*|Srr)rgrss r__next__zClosingIterator.__next__ szz||rc.|jD] }| dSrr)rl)rmcallbacks rrczClosingIterator.closes*  H HJJJJ  rrr)r]r^r_r`rra)rr\rrOrra)__name__ __module__ __qualname____doc__rprtrwrcrrrr\r\sz2GK $$$$$&rr\ file buffer_sizer8r^cL|dt||S)aWraps a file. This uses the WSGI server's file wrapper if available or otherwise the generic :class:`FileWrapper`. .. versionadded:: 0.5 If the file wrapper from the WSGI server is used it's important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set :attr:`Response.direct_passthrough` to `True`. More information about file wrappers are available in :pep:`333`. :param file: a :class:`file`-like object with a :meth:`~file.read` method. :param buffer_size: number of bytes for one iteration. zwsgi.file_wrapper)r/ FileWrapper)rrrs r wrap_filers,$ 97;;*K 8 8 k  rcLeZdZdZddd Zdd Zdd ZddZddZddZ ddZ dS)ra\This class can be used to convert a :class:`file`-like object into an iterable. It yields `buffer_size` blocks until the file is fully read. You should not use this class directly but rather use the :func:`wrap_file` function that uses the WSGI server's file wrapper support if it's available. .. versionadded:: 0.5 If you're using this object together with a :class:`Response` you have to use the `direct_passthrough` mode. :param file: a :class:`file`-like object with a :meth:`~file.read` method. :param buffer_size: number of bytes for one iteration. rrrIrr8rrac"||_||_dSrr)rr)rmrrs rrpzFileWrapper.__init__>s &rcft|jdr|jdSdSNrc)hasattrrrcrss rrczFileWrapper.closeBs8 49g & &  IOO       rrct|jdr|jSt|jdrdSdS)NseekableseekTF)rrrrss rrzFileWrapper.seekableFsH 49j ) ) (9%%'' ' 49f % % 4urargst.AnycRt|jdr|jj|dSdS)Nr)rrr)rmrs rrzFileWrapper.seekMs7 49f % % " DIND ! ! ! ! " "rr@cbt|jdr|jSdS)Ntell)rrrrss rrzFileWrapper.tellQs- 49f % % $9>>## #trc|Srrrrss rrtzFileWrapper.__iter__VrurrOcd|j|j}|r|Strr)rreadr StopIteration)rmdatas rrwzFileWrapper.__next__Ys/y~~d.//  KoorNr)rrIrr8rrar{rr)rrrra)rr@)rrrz) r|r}r~rrprcrrrrtrwrrrrr,s"'''''"""" rrcPeZdZdZ ddd Zdd ZddZddZddZddZ ddZ dS) _RangeWrapperasThis class can be used to convert an iterable object into an iterable that will only yield a piece of the underlying content. It yields blocks until the underlying stream range is fully read. The yielded blocks will have a size that can't exceed the original iterator defined block size, but that can be smaller. If you're using this object together with a :class:`Response` you have to use the `direct_passthrough` mode. :param iterable: an iterable object with a :meth:`__next__` method. :param start_byte: byte from which read will start. :param byte_range: how many bytes to read. rNr]t.Iterable[bytes] | t.IO[bytes] start_byter8 byte_ranger@ct||_||_||_d|_| ||z|_d|_t |do||_d|_dS)NrrF) rdr]rrend_byte read_lengthrr end_reached)rmr]rrs rrpz_RangeWrapper.__init__qsp X $$  !&3DM*55M(:K:K:M:M  rrc|Srrrrss rrtz_RangeWrapper.__iter__rurrOc t|j}|xjt|z c_|S#t$r d|_wxYwNT)rfr]rlenrrrmchunks r _next_chunkz_RangeWrapper._next_chunks[ ''E   E *  L   #D   s 25Atuple[bytes | None, int]cNd}|jrE|j|j|j|_|j}nT|j|jkr$|}|j|jk$|||j|jz d}|j}||fSrr)rr]rrrrrrmrcontextual_read_lengths r_first_iterationz_RangeWrapper._first_iterations = 5 M  t / / /#}1133D %)%5 " ""do55((**"do55 do0@@BBC%)_ ",,,rc|jrtd}|j}|jdkr|\}}||}|j)|j|jkrd|_|d|j|z S|S)NrT)rrrrrrrs rrgz_RangeWrapper._nexts   "// !!%!1  q ,0,A,A,C,C )E) =$$&&E = $)9T])J)J#D A4=+AAAB B rc\|}|r|Sd|_tr)rgrrrs rrwz_RangeWrapper.__next__s.   Loorracft|jdr|jdSdSr)rr]rcrss rrcz_RangeWrapper.closes: 4=' * * " M   ! ! ! ! ! " "r)rN)r]rrr8rr@)rrrz)rrr{) r|r}r~rrprtrrrgrwrcrrrrr`s  "!% !!!!!$ - - - -    """"""rrcneZdZdZddd Zedd Zdd Zdd dZd!dZ d"dZ d!dZ d#dZ ddZ dS)$rPa:Wrap a stream so that it doesn't read more than a given limit. This is used to limit ``wsgi.input`` to the ``Content-Length`` header value or :attr:`.Request.max_content_length`. When attempting to read after the limit has been reached, :meth:`on_exhausted` is called. When the limit is a maximum, this raises :exc:`.RequestEntityTooLarge`. If reading from the stream returns zero bytes or raises an error, :meth:`on_disconnect` is called, which raises :exc:`.ClientDisconnected`. When the limit is a maximum and zero bytes were read, no error is raised, since it may be the end of the stream. If the limit is reached before the underlying stream is exhausted (such as a file that is too large, or an infinite stream), the remaining contents of the stream cannot be read safely. Depending on how the server handles this, clients may show a "connection reset" failure instead of seeing the 413 response. :param stream: The stream to read from. Must be a readable binary IO object. :param limit: The limit in bytes to not read past. Should be either the ``Content-Length`` header value or ``request.max_content_length``. :param is_max: Whether the given ``limit`` is ``request.max_content_length`` instead of the ``Content-Length`` header value. This changes how exhausted and disconnect events are handled. .. versionchanged:: 2.3 Handle ``max_content_length`` differently than ``Content-Length``. .. versionchanged:: 2.3 Implements ``io.RawIOBase`` rather than ``io.IOBase``. FrSrIlimitr8rKrrrac>||_d|_||_||_dS)Nr)_stream_posr _limit_is_max)rmrSrrKs rrpzLimitedStream.__init__s%   #rc"|j|jkS)z:Whether the current stream position has reached the limit.)rrrss r is_exhaustedzLimitedStream.is_exhaustedsyDJ&&rc0|jrtdS)aCalled when attempting to read after the limit has been reached. The default behavior is to do nothing, unless the limit is a maximum, in which case it raises :exc:`.RequestEntityTooLarge`. .. versionchanged:: 2.3 Raises ``RequestEntityTooLarge`` if the limit is a maximum. .. versionchanged:: 2.3 Any return value is ignored. N)rr rss r on_exhaustedzLimitedStream.on_exhausteds%   *')) ) * *rNerrorException | Nonec4|jr|tdS)aCalled when an attempted read receives zero bytes before the limit was reached. This indicates that the client disconnected before sending the full request body. The default behavior is to raise :exc:`.ClientDisconnected`, unless the limit is a maximum and no error was raised. .. versionchanged:: 2.3 Added the ``error`` parameter. Do nothing if the limit is a maximum and no error was raised. .. versionchanged:: 2.3 Any return value is ignored. N)rr)rmrs r on_disconnectzLimitedStream.on_disconnects(! 'U%6$&& &&7%6rrOc<|js|SdS)a>Exhaust the stream by reading until the limit is reached or the client disconnects, returning the remaining data. .. versionchanged:: 2.3 Return the remaining data. .. versionchanged:: 2.2.3 Handle case where wrapped stream returns fewer bytes than requested. r)rreadallrss rexhaustzLimitedStream.exhausts"  "<<>> !srb bytearrayr@cbt|}|j|jz }|dkr|dSt |jdr||krR |j|}n#ttf$r!}| |Yd}~dSd}~wwxYwt|} |j|}n5#ttf$r!}| |Yd}~dSd}~wwxYw|r||d|<nu |j t||}n5#ttf$r!}| |Yd}~dSd}~wwxYwt|}||d|<|s| dS|xj|z c_|S)Nrreadinto)r) rrrrrrrOSErrorr:rrrmin)rmrsize remainingout_sizeetemp_brs rrzLimitedStream.readintos1vvJ* >>      1 4< , , y  +/<+@+@+C+CHH,&&Q&///11111 #9--#|44V<>Z(   """+++qqqqq 4yyHAixiL     1 X sHA33B%B  B%8CD$DD(D<<E. E))E.c|jr|dSt}|js4|d}|sn|||j4t |S)Nri)rrrrextendrO)rmoutrs rrzLimitedStream.readallFs         3kk# 99Y''D  JJt   # Szzrc|jS)zKReturn the current stream position. .. versionadded:: 0.9 )rrss rrzLimitedStream.tellYs yrcdSrrrss rreadablezLimitedStream.readable`str)F)rSrIrr8rKrrrarr{rr)rrrrarz)rrrr@)rr8)r|r}r~rrppropertyrrrrrrrrrrrrPrPs>$$$$$ '''X' * * * *''''',    ....`&rrP)rrrr )FFFN) rr rrrrrrrr rr!)rr rr4rr)rr rr rr!)rr rr@)TN)rr rGrrHr@rrI)rr rr!r)rr rrIrr8rr^)! __future__rrQtypingrL functoolsrr exceptionsrr sansior r1 sansio.utilsr TYPE_CHECKING_typeshed.wsgir r rr2r=r.rFrUrZr\rrr RawIOBaserPrrrrsn"""""" $$$$$$******------******))))))?/............ 8 8 8 8#.2 #2#2#2#2#2L$IM'''''T    "%)AFAFAFAFAFH ) ) ) )11111111jEI.11111111hT"T"T"T"T"T"T"T"njjjjjBLjjjjjr