o 7]h+n@sTddlmZddlZddlZddlZddlmZddlmZ ddlm Z zddl Z Wn e y5dZ YnwddlmZddlmZmZdd lmZmZmZmZmZmZmZmZmZmZdd lmZdd l m!Z!m"Z"e#e$Z%Gd d d e&Z'Gddde&Z(Gddde&Z)e durGddde&Z*Gddde&Z+ddZ,Gdddej-Z.dS))absolute_importN)contextmanager)error)timeout)HTTPHeaderDict) BaseSSLError HTTPException) BodyNotHttplibCompatible DecodeError HTTPErrorIncompleteReadInvalidChunkLength InvalidHeader ProtocolErrorReadTimeoutErrorResponseNotChunkedSSLError)six) is_fp_closedis_response_to_headc@$eZdZddZddZddZdS)DeflateDecodercCsd|_d|_t|_dS)NT) _first_try_datazlib decompressobj_objselfr!>/usr/lib/python3/dist-packages/pip/_vendor/urllib3/response.py__init__$szDeflateDecoder.__init__cC t|j|SNgetattrrr namer!r!r" __getattr__) zDeflateDecoder.__getattr__c Cs|s|S|js |j|S|j|7_z|j|}|r#d|_d|_|WStjyId|_ttj |_z ||jWd|_YSd|_ww)NF)rr decompressrrrr MAX_WBITS)r data decompressedr!r!r"r,,s$   zDeflateDecoder.decompressN__name__ __module__ __qualname__r#r*r,r!r!r!r"r#s rc@seZdZdZdZdZdS)GzipDecoderStaterrN)r1r2r3 FIRST_MEMBER OTHER_MEMBERS SWALLOW_DATAr!r!r!r"r4Csr4c@r) GzipDecodercCstdtj|_tj|_dS)N)rrr-rr4r6_staterr!r!r"r#Ks zGzipDecoder.__init__cCr$r%r&r(r!r!r"r*Or+zGzipDecoder.__getattr__cCst}|jtjks |st|S z ||j|7}Wntjy5|j}tj|_|tj kr4t|YSw|jj }|s@t|Stj |_t dtj |_q)NTr:) bytearrayr;r4r8bytesrr,rrr7 unused_datarr-)r r.retprevious_stater!r!r"r,Rs&  zGzipDecoder.decompressNr0r!r!r!r"r9Js r9c@seZdZddZddZdS) BrotliDecodercCs2t|_t|jdr|jj|_dS|jj|_dS)Nr,)brotli Decompressorrhasattrr,processrr!r!r"r#ns  zBrotliDecoder.__init__cCst|jdr |jSdS)Nflushr)rDrrFrr!r!r"rFus  zBrotliDecoder.flushN)r1r2r3r#rFr!r!r!r"rAjs rAc@s(eZdZdZddZddZddZdS) MultiDecodera From RFC7231: If one or more encodings have been applied to a representation, the sender that applied the encodings MUST generate a Content-Encoding header field that lists the content codings in the order in which they were applied. cCsdd|dD|_dS)NcSsg|]}t|qSr!) _get_decoderstrip).0mr!r!r" sz)MultiDecoder.__init__..,)split _decoders)r modesr!r!r"r#szMultiDecoder.__init__cCs|jdSNr)rOrFrr!r!r"rFzMultiDecoder.flushcCst|jD]}||}q|Sr%)reversedrOr,)r r.dr!r!r"r,s zMultiDecoder.decompressN)r1r2r3__doc__r#rFr,r!r!r!r"rG{s  rGcCs:d|vrt|S|dkrtStdur|dkrtStS)NrMgzipbr)rGr9rBrAr)moder!r!r"rHsrHc@seZdZdZddgZeduredg7ZgdZ              dJd d Zd dZddZ ddZ e ddZ e ddZ ddZddZddZddZeejfZedurdeejf7Zdd Zd!d"Zed#d$ZdKd%d&ZdLd(d)Zed*d+Zd,d-ZdMd.d/Zd0d1Z d2d3Z!e d4d5Z"d6d7Z#d8d9Z$d:d;Z%dd?Z'd@dAZ(dBdCZ)dNdDdEZ*dFdGZ+dHdIZ,dS)O HTTPResponsea HTTP Response container. Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, and can hence be treated as a readable object in the context of that framework. Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param original_response: When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse` object, it's convenient to include the original for debug purposes. It's otherwise unused. :param retries: The retries contains the last :class:`~urllib3.util.retry.Retry` that was used during the request. :param enforce_content_length: Enforce content length checking. Body returned by server must match value of Content-Length header, if present. Otherwise, raise error. rVdeflateNrW)i-i.i/i3i4rTFcCst|tr ||_nt||_||_||_||_||_||_| |_||_ ||_ d|_ d|_ d|_ | |_d|_| |_||_|rHt|tjtfrH||_ | |_| |_t|drV||_ d|_d|_|jdd}dd|dD}d |vrvd |_|||_|r|j s|j|d |_ dSdSdS) NrreadFztransfer-encodingr[css|]}|VqdSr%)rI)rJencr!r!r" sz(HTTPResponse.__init__..rMchunkedTdecode_content) isinstancerheadersstatusversionreasonstrictraretriesenforce_content_length auto_close_decoder_body_fp_original_response_fp_bytes_readmsg _request_urlr string_typesr=_pool _connectionrDr_ chunk_leftgetlowerrN _init_lengthlength_remainingr\)r bodyrcrdrerfrgpreload_contentraoriginal_responsepool connectionrprhrirequest_method request_urlrjtr_enc encodingsr!r!r"r#sD     zHTTPResponse.__init__cCs|j|jvr |jdSdS)a Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. locationF)rdREDIRECT_STATUSESrcrvrr!r!r"get_redirect_locations  z"HTTPResponse.get_redirect_locationcCs(|jr|jsdS|j|jd|_dSr%)rsrt _put_connrr!r!r" release_conns  zHTTPResponse.release_connc Cs,z|WdSttttfyYdSw)z Read and discard any remaining HTTP response data in the response connection. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool. N)r\r SocketErrorrr rr!r!r" drain_conns zHTTPResponse.drain_conncCs"|jr|jS|jr|jddSdS)NT) cache_content)rlrmr\rr!r!r"r.%s  zHTTPResponse.datacC|jSr%)rtrr!r!r"r~.szHTTPResponse.connectioncCs t|jSr%)rrmrr!r!r"isclosed2s zHTTPResponse.isclosedcCr)z Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``urllib3.response.HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). )rorr!r!r"tell5szHTTPResponse.tellcCs|jd}|durD|jrtddSztdd|dD}t|dkr-td|| }Wn t y=d}Ynw|d krDd}zt |j }Wn t yVd }Ynw|d vsjd |kred ksjn|d krld }|S)zM Set initial length value for Response content if available. zcontent-lengthNzReceived response with both Content-Length and Transfer-Encoding set. This is expressly forbidden by RFC 7230 sec 3.3.2. Ignoring Content-Length and attempting to process response as Transfer-Encoding: chunked.cSsg|]}t|qSr!)int)rJvalr!r!r"rLWsz-HTTPResponse._init_length..rMrz8Content-Length contained multiple unmatching values (%s)r)i0dHEAD) rcrvr_logwarningsetrNlenrpop ValueErrorrrd)r rlengthlengthsrdr!r!r"rx=s:     &zHTTPResponse._init_lengthcsvjdd}jdur5|jvrt|_dSd|vr7fdd|dD}t|r9t|_dSdSdSdS)z= Set-up the _decoder attribute if necessary. content-encodingr[NrMcs"g|] }|jvr|qSr!)rICONTENT_DECODERS)rJerr!r"rL|s z.HTTPResponse._init_decoder..)rcrvrwrkrrHrNr)r content_encodingrr!rr" _init_decoderqs   zHTTPResponse._init_decoderc Csn|s|Sz |jr|j|}Wn|jy,}z|jdd}td||d}~ww|r5||7}|S)zN Decode the data passed in and potentially flush the decoder. rr[zEReceived response with content-encoding: %s, but failed to decode it.N)rkr,DECODER_ERROR_CLASSESrcrvrwr _flush_decoder)r r.ra flush_decoderrrr!r!r"_decodes&  zHTTPResponse._decodecCs$|jr|jd}||jSdS)zk Flushes the decoder. Should only be called if the decoder is actually being used. r)rkr,rF)r bufr!r!r"rs zHTTPResponse._flush_decoderc cs d}zkzdVWn>tyt|jddty3}zdt|vr(t|t|jddd}~wttfyG}ztd||d}~wwd}W|s]|j rU|j |j r]|j |j rk|j rm| dSdSdS|s|j ry|j |j r|j |j r|j r| www)z Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. FNzRead timed out.zread operation timed outzConnection broken: %rT) SocketTimeoutrrsrstrrr rrrnclosertrr)r clean_exitrr!r!r"_error_catchersB          zHTTPResponse._error_catchercCs||dur |j}|jdurdSd}t|jdd}|@|dur0|s+|jnd}d}n(d}|s:|j|nd}|dkrX|sX|jd}|jrX|jdvrXt |j |jWdn1sbwY|r|j t |7_ |jdur|jt |8_| |||}|r||_ |S)aT Similar to :meth:`http.client.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) NFclosedrTr)rN)rrarmr'rr\rriryr rorrrl)r amtrarr fp_closedr.r!r!r"r\s8      zHTTPResponse.readccsb|jr|r|j||dD]}|VqdSt|js/|j||d}|r(|Vt|jrdSdS)a_ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. r`)rraN)r_supports_chunked_reads read_chunkedrrmr\)r rraliner.r!r!r"stream+s zHTTPResponse.streamc Ksb|j}t|tstjrt|}nt|}t|dd}|d|||j|j |j ||d|}|S)a Given an :class:`http.client.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. rgr)rzrcrdrerfrgr|Nr!) rprbrrPY2 from_httplibitemsr'rdrerf) ResponseClsr response_kwrcrgrespr!r!r"rEs$     zHTTPResponse.from_httplibcCrr%rcrr!r!r" getheadersfzHTTPResponse.getheaderscCs|j||Sr%)rcrv)r r)defaultr!r!r" getheaderirRzHTTPResponse.getheadercCrr%rrr!r!r"infomrzHTTPResponse.infocCs:|js|j|jr|j|jstj|dSdSr%)rrmrrtrjioIOBaserr!r!r"rqs  zHTTPResponse.closecCsP|js tjj|S|jdurdSt|jdr|jSt|jdr&|jjSdS)NTrr)rjrrr__get__rmrDrrr!r!r"r{s    zHTTPResponse.closedcCs0|jdur tdt|jdr|jStd)Nz-HTTPResponse has no file to get a fileno fromfilenozOThe file-like object this HTTPResponse is wrapped around has no file descriptor)rmIOErrorrDrrr!r!r"rs   zHTTPResponse.filenocCs:|jdurt|jdrt|jdds|jSdSdSdS)NrFrF)rmrDr'rFrr!r!r"rFs     zHTTPResponse.flushcCsdS)NTr!rr!r!r"readableszHTTPResponse.readablecCs6|t|}t|dkrdS||dt|<t|SrQ)r\r)r btempr!r!r"readintos  zHTTPResponse.readintocCs t|jdS)a Checks if the underlying file-like object looks like a :class:`http.client.HTTPResponse` object. We do this by testing for the fp attribute. If it is present we assume it returns raw chunks as processed by read_chunked(). fp)rDrmrr!r!r"rs z#HTTPResponse.supports_chunked_readscCs^|jdurdS|jj}|ddd}z t|d|_WdSty.|t||w)N;rrr:) rurmrreadlinerNrrrr)r rr!r!r"_update_chunk_lengths    z!HTTPResponse._update_chunk_lengthcCsd}|dur|j|j}|}|jdd|_|S||jkr/|j|}|j||_|}|S||jkrG|j|}|jdd|_|}|S|j|j}|jdd|_|S)Nr5)rm _safe_readru)r rreturned_chunkchunkvaluer!r!r" _handle_chunks,      zHTTPResponse._handle_chunkccs2||js td|std|w|jr/t|jr/|j WddS|j j dur> WddS | |j dkrIn| |}|j||dd}|r[|Vq?|rg|}|rg|V |j j }|sqn|dkrvnqh|jr|jWddSWddS1swYdS) a Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. zHResponse is not chunked. Header 'transfer-encoding: chunked' is missing.zkBody should be http.client.HTTPResponse like. It should have have an fp attribute which returns raw chunks.NTrF)rars )rr_rrr rrnrrrmrrrurrrr)r rrardecodedrr!r!r"rsZ         ("zHTTPResponse.read_chunkedcCs*|jdurt|jjr|jjdjS|jS)z Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. N)rhrhistoryredirect_locationrqrr!r!r"geturlszHTTPResponse.geturlccsg}|jddD]7}d|vr;|d}d||ddV|ddD]}|dVq&|dr8|dg}q g}q ||q |rKd|VdSdS)NTr` rrrr)rrNjoinappend)r bufferrxr!r!r"__iter__&s    zHTTPResponse.__iter__)r[NrrNrTTNNNNNFNNT)NNF)rNr%)NN)-r1r2r3rUrrBrr#rrrpropertyr.r~rrrxrrrrrrrrrr\r classmethodrrrrrrrrFrrrrrrrrr!r!r!r"rYs|   C   4    7 J        F rY)/ __future__rrloggingr contextlibrsocketrrrrrB ImportError _collectionsrr~rr exceptionsr r r r rrrrrrpackagesr util.responserr getLoggerr1robjectrr4r9rArGrHrrYr!r!r!r"s4       0