o gn@sPddlmZddlZddlZddlZddlmZddlmZ ddlm Z zddl Z Wn e y5dZ YnwddlmZddlmZmZdd lmZmZmZmZmZmZmZmZmZmZddlZdd lm Z m!Z!e"e#Z$Gd d d e%Z&Gd dde%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) is_fp_closedis_response_to_headc@$eZdZddZddZddZdS)DeflateDecodercCsd|_d|_t|_dS)NT) _first_try_datazlib decompressobj_objselfr 2/usr/lib/python3/dist-packages/urllib3/response.py__init__$szDeflateDecoder.__init__cC t|j|SNgetattrrrnamer 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)rdata decompressedr r r!r+,s$   zDeflateDecoder.decompressN__name__ __module__ __qualname__r"r)r+r r r r!r#s rc@seZdZdZdZdZdS)GzipDecoderStaterrN)r0r1r2 FIRST_MEMBER OTHER_MEMBERS SWALLOW_DATAr r r r!r3Csr3c@r) GzipDecodercCstdtj|_tj|_dS)N)rrr,rr3r5_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)NTr9) bytearrayr:r3r7bytesrr+rrr6 unused_datarr,)rr-retprevious_stater r r!r+Rs&  zGzipDecoder.decompressNr/r r r r!r8Js r8c@seZdZddZddZdS) BrotliDecodercCs2t|_t|jdr|jj|_dS|jj|_dS)Nr+)brotli Decompressorrhasattrr+processrr r r!r"ns  zBrotliDecoder.__init__cCst|jdr |jSdS)Nflushr)rCrrErr r r!rEus  zBrotliDecoder.flushN)r0r1r2r"rEr r r r!r@js r@c@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)rmodesr r r!r"szMultiDecoder.__init__cCs|jdSNr)rNrErr r r!rEzMultiDecoder.flushcCst|jD]}||}q|Sr$)reversedrNr+)rr-dr r r!r+s zMultiDecoder.decompressN)r0r1r2__doc__r"rEr+r r r r!rF{s  rFcCs:d|vrt|S|dkrtStdur|dkrtStS)NrLgzipbr)rFr8rAr@r)moder r r!rGsrGc@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. rUdeflateNrV)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-encodingrZcss|]}|VqdSr$)rH)rIencr r r! sz(HTTPResponse.__init__..rLchunkedTdecode_content) isinstancerheadersstatusversionreasonstrictr`retriesenforce_content_length auto_close_decoder_body_fp_original_response_fp_bytes_readmsg _request_urlsix string_typesr<_pool _connectionrCr^ chunk_leftgetlowerrM _init_lengthlength_remainingr[)rbodyrbrcrdrerfpreload_contentr`original_responsepool connectionrorgrhrequest_method request_urlritr_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)rcREDIRECT_STATUSESrbrvrr 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)rkrlr[rr r r!r-%s  zHTTPResponse.datacC|jSr$)rtrr r r!r~.szHTTPResponse.connectioncCs t|jSr$)rrlrr 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). )rnrr 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)rIvalr r r!rKWsz-HTTPResponse._init_length..rLrz8Content-Length contained multiple unmatching values (%s)r)i0dHEAD) rbrvr^logwarningsetrMlenrpop ValueErrorrrc)rrlengthlengthsrcr r r!rx=s:     &zHTTPResponse._init_lengthcsvjdd}jdur5|jvrt|_dSd|vr7fdd|dD}t|r9t|_dSdSdSdS)z= Set-up the _decoder attribute if necessary. content-encodingrZNrLcs"g|] }|jvr|qSr )rHCONTENT_DECODERS)rIerr r!rK|s z.HTTPResponse._init_decoder..)rbrvrwrjrrGrMr)rcontent_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. rrZzEReceived response with content-encoding: %s, but failed to decode it.N)rjr+DECODER_ERROR_CLASSESrbrvrwr _flush_decoder)rr-r` 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)rjr+rE)rbufr 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 rrrmclosertrr)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)rr`rlr&rr[rrhryr rnrrrk)ramtr`rr 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_)rr`N)r^supports_chunked_reads read_chunkedrrlr[)rrr`liner-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``. rfr)rzrbrcrdrerfr|Nr ) rorarrqPY2 from_httplibitemsr&rcrdre) ResponseClsr response_kwrbrfrespr r r!rEs$     zHTTPResponse.from_httplibcCrr$rbrr r r! getheadersfzHTTPResponse.getheaderscCs|j||Sr$)rbrv)rr(defaultr r r! getheaderirQzHTTPResponse.getheadercCrr$rrr r r!infomrzHTTPResponse.infocCs:|js|j|jr|j|jstj|dSdSr$)rrlrrtriioIOBaserr r r!rqs  zHTTPResponse.closecCsP|js tjj|S|jdurdSt|jdr|jSt|jdr&|jjSdS)NTrr)rirrr__get__rlrCrrr 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)rlIOErrorrCrrr r r!rs   zHTTPResponse.filenocCs:|jdurt|jdrt|jdds|jSdSdSdS)NrErF)rlrCr&rErr r r!rEs     zHTTPResponse.flushcCsdS)NTr rr r r!readableszHTTPResponse.readablecCs6|t|}t|dkrdS||dt|<t|SrP)r[r)rbtempr 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)rCrlrr r r!rs z#HTTPResponse.supports_chunked_readscCs^|jdurdS|jj}|ddd}z t|d|_WdSty.|t||w)N;rrr9) rurlrreadlinerMrrrr)rrr 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)Nr4)rl _safe_readru)rrreturned_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)r`rs )rr^rrr rrmrrrlrrrurrrr)rrr`rdecodedrr 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)rgrhistoryredirect_locationrprr r r!geturlszHTTPResponse.geturlccsg}|jddD]7}d|vr;|d}d||ddV|ddD]}|dVq&|dr8|dg}q g}q ||q |rKd|VdSdS)NTr_ rrrr)rrMjoinappend)rbufferrxr r r!__iter__&s    zHTTPResponse.__iter__)rZNrrNrTTNNNNNFNNT)NNF)rNr$)NN)-r0r1r2rTrrArr"rrrpropertyr-r~rrrxrrrrrrrrrr[r classmethodrrrrrrrrErrrrrrrrr r r r!rXs|   C   4    7 J        F rX). __future__rrloggingr contextlibrsocketrrrrrA ImportError _collectionsrr~rr exceptionsr r r r rrrrrrrq util.responserr getLoggerr0robjectrr3r8r@rFrGrrXr r r r!s4       0