U ai@sddlZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddl m Z ddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZej r ddl!Z"ddl#m$Z$ddl#m%Z%ddl#m&Z&ej'ddddZ(ej'ej)e*e+fe*ej,e+dddZ-ej)e.e*fe*dddZ/Gd d!d!e Z Gd"d#d#Z0Gd$d%d%Z1dS)&N) HTTPStatus) _to_bytes)Headers)remove_entity_headers)Response) iri_to_uri)url_join)cached_property)ClosingIterator)get_current_url) _get_environ) generate_etag) http_date)is_resource_modified) parse_etags)parse_range_header) _RangeWrapper) StartResponse)WSGIApplication)WSGIEnvironment)iterablereturncCst|trtjddddS)znHelper for the response objects to check if the iterable returned to the WSGI server is not a string. zResponse iterable was set to a string. This will appear to work but means that the server will send the data to the client one character at a time. This is almost never intended behavior, use 'response.data' to assign strings to the response object.r stacklevelN) isinstancestrwarningswarn)rr[C:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-1tps7o9u\werkzeug\wrappers\response.py_warn_if_strings  r!)rcharsetrccs,|D]"}t|tr ||Vq|VqdSN)rrencode)rr"itemrrr _iter_encoded.s r&) accept_rangesrcCs2|dkr dS|dkrdSt|tr&|StddS)NTbytesFnonezInvalid accept_ranges value)rr ValueError)r'rrr _clean_accept_ranges8s r+cseZdZUdZdZdZdZejej e ej e fe d<dZej ejej e e ej e e fej ejee efej ejeje eje eej eje efffej eje eje efffej e ej e eddfdd Zejgejfejgejfd d d Ze d d dZed[dej dddddZed\ddeddddZejd]de dddZejde dddZd^eeje e fdddZeje e fdddd Zeeed!d"Z ej ed d#d$Z!d_edd%d&d'Z"dd d(d)Z#ej$e d d*d+Z%eed d,d-Z&eed d.d/Z'dd d0d1Z(dd d2d3Z)d4d5Z*d`ddd6d7d8Z+de,d9d:d;Z-dej e d9dd?Z0dd@ej e dAdBdCZ1e2Z3eej ejd dDdEZ2daeeej ejdFdGdHZ4e5dId dJdKZ6eeddLdMdNZ7ded9dOdPZ8dbdej eej ejee fedQdRdSZ9dcdejee fej eddTdUdVZ:ddeeddWdXdYZ;Z) is_sequencesummaplen iter_encoded is_streamedtype__name__r-)r7Z body_inforrr __repr__szResponse.__repr__r)r,environrcCs>t|ts4|dkrtdddlm}t|||}||_|S)aEnforce that the WSGI response is a response object of the current type. Werkzeug will use the :class:`Response` internally in many situations like the exceptions. If you call :meth:`get_response` on an exception you will get back a regular :class:`Response` object, even if you are using a custom subclass. This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided:: # convert a Werkzeug response object into an instance of the # MyResponseClass subclass. response = MyResponseClass.force_type(response) # convert any WSGI application into a response object response = MyResponseClass.force_type(response, environ) This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass. Keep in mind that this will modify response objects in place if possible! :param response: a response object or wsgi application. :param environ: a WSGI environment object. :return: a response object. NzHcannot convert WSGI application into response objects without an environr run_wsgi_app)rr TypeErrortestrLr9)clsr,rJrLrrr force_types  zResponse.force_typer)apprJbufferedrcCsddlm}|||||S)aCreate a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the `write()` callable returned by the `start_response` function. This tries to resolve such edge cases automatically. But if you don't get the expected output you should set `buffered` to `True` which enforces buffering. :param app: the WSGI application to execute. :param environ: the WSGI environment to execute against. :param buffered: set to `True` to enforce buffering. :return: a response object. rrK)rNrL)rOrQrJrRrLrrr from_app s zResponse.from_appzte.Literal[False])as_textrcCsdSr#rr7rTrrr get_data szResponse.get_datazte.Literal[True]cCsdSr#rrUrrr rV$scCs*|d|}|r&||jS|S)aThe string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting :attr:`implicit_sequence_conversion` to `False`. If `as_text` is set to `True` the return value will be a decoded string. .. versionadded:: 0.9 )_ensure_sequencejoinrEdecoder")r7rTrvrrr rV(s  valuercCsDt|tr||j}nt|}|g|_|jr@tt||jd<dS)zSets a new string as response. The value must be a string or bytes. If a string is set it's encoded to the charset of the response (utf-8 by default). .. versionadded:: 0.9 Content-LengthN) rrr$r"r(r, automatically_set_content_lengthrDr.r7r]rrr r6=s zResponse.set_dataz>A descriptor that calls :meth:`get_data` and :meth:`set_data`.)doccCs:z |Wntk r"YdSXtdd|DS)zZsz4Response.calculate_content_length..)rX RuntimeErrorrBrEr7rrr calculate_content_lengthTs  z!Response.calculate_content_length)mutablercCsN|jr&|r"t|jts"t|j|_dS|jr4td|jsBtd|dS)zThis method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. .. versionadded:: 0.6 Nz]Attempted implicit sequence conversion but the response object is in direct passthrough mode.zThe response object required the iterable to be a sequence, but the implicit conversion was disabled. Call make_sequence() yourself.)rArr,listr1rfimplicit_sequence_conversion make_sequence)r7rirrr rX\s zResponse._ensure_sequencecCs8|js4t|jdd}t||_|dk r4||dS)aCConverts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. .. versionadded:: 0.6 closeN)rAgetattrr,rjrEr=)r7rmrrr rlus zResponse.make_sequencecCst|jt|j|jS)aIter the response encoded with the encoding of the response. If the response object is invoked as WSGI application the return value of this method is used as application iterator unless :attr:`direct_passthrough` was activated. )r!r,r&r"rgrrr rEs zResponse.iter_encodedc Cs.zt|jWnttfk r(YdSXdS)aIf the response is streamed (the response is not an iterable with a length information) this property is `True`. In this case streamed means that there is no information about the number of iterations. This is usually `True` if a generator is passed to the response object. This is useful for checking before applying some sort of post filtering that should not take place for streamed responses. TF)rDr,rMAttributeErrorrgrrr rFs zResponse.is_streamedcCst|jttfS)zIf the iterator is buffered, this property will be `True`. A response object will consider an iterator to be buffered if the response attribute is a list or tuple. .. versionadded:: 0.6 )rr,tuplerjrgrrr rAszResponse.is_sequencecCs,t|jdr|j|jD] }|qdS)zClose the wrapped response if possible. You can also use the object in a with statement which will automatically close it. .. versionadded:: 0.9 Can now be used in a with statement. rmN)hasattrr,rmr4r<rrr rms   zResponse.closecCs|Sr#rrgrrr __enter__szResponse.__enter__cCs |dSr#)rm)r7exc_type exc_valuetbrrr __exit__szResponse.__exit__)no_etagrcCsLt||_tttt|j|jd<|dk r@tj dt dd| dS)aOMake the response object ready to be pickled. Does the following: * Buffer the response into a list, ignoring :attr:`implicity_sequence_conversion` and :attr:`direct_passthrough`. * Set the ``Content-Length`` header. * Generate an ``ETag`` header if one is not already set. .. versionchanged:: 2.0 An ``ETag`` header is added, the ``no_etag`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.6 The ``Content-Length`` header is set. r^NzJThe 'no_etag' parameter is deprecated and will be removed in Werkzeug 2.1.rr) rjrEr,rrBrCrDr.rrDeprecationWarningadd_etag)r7rwrrr freezeszResponse.freeze)rJrc Cst|j}d}d}d}|j}|D]8\}}|} | dkr>|}q | dkrL|}q | dkr |}q |dk r|} t|tr|t|dd}|jrt|dd} t| trt| } t | |}|| kr||d<|dk rt|trt||d <d |krd ksn|d kr| d n|dkrt ||j r|j r|dkr|dkrd |krRd ksnztdd|jD}Wntk rYnXt||d <|S)akThis is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the location header (if present) is joined with the root URL of the environment. Also the content length is automatically set to zero here for certain status codes. .. versionchanged:: 0.6 Previously that function was called `fix_headers` and modified the response object in place. Also since 0.6, IRIs in location and content-location headers are handled properly. Also starting with 0.6, Werkzeug will attempt to set the content length if it is able to figure it out on its own. This is the case if all the strings in the response iterable are already encoded and the iterable is buffered. :param environ: the WSGI environment of the request. :return: returns a new :class:`~werkzeug.datastructures.Headers` object. Nlocationzcontent-locationcontent-lengthT)Zsafe_conversion)Zstrip_querystringZLocationzContent-Locationdr^0rrcss|]}tt|dVqdS)asciiN)rDrrbrrr re2sz,Response.get_wsgi_headers..)rr. status_codelowerrrrautocorrect_location_headerr r removerr_rArBr, UnicodeError) r7rJr.r{content_locationcontent_lengthr-keyr]ikeyZ old_locationZ current_urlrrr get_wsgi_headerssb              zResponse.get_wsgi_headerscCs`|j}|ddks0d|kr&dks0n|dkr6d}n|jrLt|j|jS|}t||jS)aReturns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: a response iterable. REQUEST_METHODHEADr}r~rr)rr1r!r,rEr rm)r7rJr-rrrr get_app_iter<s   zResponse.get_app_itercCs$||}||}||j|fS)aFReturns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is ``'HEAD'`` the response will be empty and only the headers and status code will be present. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: an ``(app_iter, status, headers)`` tuple. )rrr-Z to_wsgi_list)r7rJr.app_iterrrr get_wsgi_responseYs  zResponse.get_wsgi_responser)rJstart_responsercCs||\}}}||||S)zProcess this response as WSGI application. :param environ: the WSGI environment. :param start_response: the response callable provided by the WSGI server. :return: an application iterator )r)r7rJrrr-r.rrr __call__ls  zResponse.__call__cCs|S)zThe parsed JSON data if :attr:`mimetype` indicates JSON (:mimetype:`application/json`, see :meth:`is_json`). Calls :meth:`get_json` with default arguments. )get_jsonrgrrr jsonsz Response.json)forcesilentrcCsF|s|jsdS|}z|j|WStk r@|s:YdSXdS)aParse :attr:`data` as JSON. Useful during testing. If the mimetype does not indicate JSON (:mimetype:`application/json`, see :meth:`is_json`), this returns ``None``. Unlike :meth:`Request.get_json`, the result is not cached. :param force: Ignore the mimetype and always try to parse JSON. :param silent: Silence parsing errors and return ``None`` instead. N)Zis_jsonrV json_moduleloadsr*)r7rrdatarrr rs zResponse.get_jsonResponseStreamcCst|S)z+The response iterable as write-only stream.)rrgrrr streamszResponse.stream)startlengthrcCs|jdkrt|j|||_dS)z8Wrap existing Response in case of Range Request context.N)rrr,)r7rrrrr _wrap_range_responses zResponse._wrap_range_responsecCs4d|ks,t||jdd|jddd o2d|kS)zReturn ``True`` if `Range` header is present and if underlying resource is considered unchanged when compared with `If-Range` header. Z HTTP_IF_RANGEetagN last-modifiedF)Zignore_if_range HTTP_RANGE)rr.get)r7rJrrr _is_range_request_processables   z&Response._is_range_request_processable)rJcomplete_lengthr'rc Csddlm}|dks.|dks.|dks.||s2dSt|d}|dkrP||||}||}|dkst|dkr||||d|d}||jd<||jd <||_d |_ | |d|d S) a.Handle Range Request related headers (RFC7233). If `Accept-Ranges` header is valid, and Range Request is processable, we set the headers as described by the RFC, and wrap the underlying response in a RangeWrapper. Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise. :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable` if `Range` header could not be parsed or satisfied. .. versionchanged:: 2.0 Returns ``False`` if the length is 0. r)RequestedRangeNotSatisfiableNrFrr^z Accept-RangesrT) exceptionsrrrrZrange_for_lengthZto_content_range_headerr.Z content_rangerr) r7rJrr'rZ parsed_rangeZ range_tupleZcontent_range_headerrrrr _process_range_requests0     zResponse._process_range_request)request_or_environr'rrcCst|}|ddkrd|jkr*t|jd<t|}||||}|s~t||jdd|jds~t|drxd |_nd |_|j rd |jkr| }|dk r||jd <|S) aMake the response conditional to the request. This method works best if an etag was defined for the response already. The `add_etag` method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is anything but GET or HEAD. For optimal performance when handling range requests, it's recommended that your response data object implements `seekable`, `seek` and `tell` methods as described by :py:class:`io.IOBase`. Objects returned by :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods. It does not remove the body of the response because that's something the :meth:`__call__` function does for us automatically. Returns self so that you can do ``return resp.make_conditional(req)`` but modifies the object in-place. :param request_or_environ: a request object or WSGI environment to be used to make the response conditional against. :param accept_ranges: This parameter dictates the value of `Accept-Ranges` header. If ``False`` (default), the header is not set. If ``True``, it will be set to ``"bytes"``. If ``None``, it will be set to ``"none"``. If it's a string, it will use this value. :param complete_length: Will be used only in valid Range Requests. It will set `Content-Range` complete length value and compute `Content-Length` real value. This parameter is mandatory for successful Range Requests completion. :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable` if `Range` header could not be parsed or satisfied. .. versionchanged:: 2.0 Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error. r)GETrdateDaterNrZ HTTP_IF_MATCHirr|r^) r r.rr+rrrrrr_rh)r7rr'rrJZis206rrrr make_conditionals..      zResponse.make_conditional) overwriteweakrcCs&|sd|jkr"|t||dS)zAdd an etag for the current response if there is none yet. .. versionchanged:: 2.0 SHA-1 is used to generate the value. MD5 may not be available in some environments. rN)r.Zset_etagrrV)r7rrrrr ry9szResponse.add_etag)NNNNNF)N)F)F)F)F)N)FF)NN)FN)FF)=rH __module__ __qualname____doc__rkrr_tUnionIterablerr(__annotations__OptionalintrMappingTupleboolr3CallableAnyr=rI classmethodrPrStypingoverloadrVr6propertyrrhrXrlIteratorrErFrArmrrrvrzrrrListrrrrrr rrrrrry __classcell__rrr8r rBs K ((( ,    ]$   3  Krc@seZdZdZdZedddZeedddZ e j ed d d d Z d d ddZ d d ddZed ddZed ddZeed ddZd S)rzA file descriptor like object used by the :class:`ResponseStreamMixin` to represent the body of the stream. It directly pushes into the response iterable of the response object. zwb+)r,cCs||_d|_dS)NF)r,closed)r7r,rrr r3LszResponseStream.__init__r\cCsB|jrtd|jjdd|jj||jjddt|S)NI/O operation on closed fileT)rir^)rr*r,rXr;r.poprDr`rrr writePs zResponseStream.writeN)seqrcCs|D]}||qdSr#)r)r7rr%rrr writelinesXszResponseStream.writelinesr>cCs d|_dS)NT)rrgrrr rm\szResponseStream.closecCs|jrtddS)Nrrr*rgrrr flush_szResponseStream.flushcCs|jrtddS)NrFrrgrrr isattycszResponseStream.isattycCs|jttt|jjSr#)r,rXrBrCrDrgrrr tellhs zResponseStream.tellcCs|jjSr#)r,r"rgrrr encodinglszResponseStream.encoding)rHrrrmoderr3r(rrrrrrmrrrrrrrrrrr rDsrcs*eZdZejejddfdd ZZS)ResponseStreamMixinN)argskwargsrcs"tjdtddtj||dS)Nz|'ResponseStreamMixin' is deprecated and will be removed in Werkzeug 2.1. 'Response' now includes the functionality directly.rr)rrrxr2r3)r7rrr8rr r3rs zResponseStreamMixin.__init__)rHrrrrr3rrrr8r rqsr)2rrrrhttpr _internalrZdatastructuresrrZsansio.responserZ_SansIOResponseurlsrr utilsr Zwsgir r Zwerkzeug._internalr Z werkzeug.httprrrrrZ werkzeug.wsgir TYPE_CHECKINGZtyping_extensionsteZ_typeshed.wsgirrrrr!rrr(rr&rr+rrrrrr sP                      -