3 PfwY@sddlmZddlmZddlZddlZddlZddlmZ ddlm Z ddl m Z ddlmZmZmZmZmZmZmZdd lmZmZmZdd lmZdd lmZm Z dd l!m"Z"m#Z#ej$e%Z&Gd dde'Z(Gddde'Z)ddZ*Gdddej+Z,dS))absolute_import)contextmanagerN)timeout)error)HTTPHeaderDict)BodyNotHttplibCompatible ProtocolError DecodeErrorReadTimeoutErrorResponseNotChunkedIncompleteRead InvalidHeader) string_types binary_typePY3) http_client) HTTPException BaseSSLError) is_fp_closedis_response_to_headc@s$eZdZddZddZddZdS)DeflateDecodercCsd|_t|_tj|_dS)NT) _first_tryr_datazlib decompressobj_obj)selfr/usr/lib/python3.6/response.py__init__szDeflateDecoder.__init__cCs t|j|S)N)getattrr)rnamerrr __getattr__szDeflateDecoder.__getattr__cCs|s|S|js|jj|S|j|7_y |jj|}|rFd|_d|_|Stjk rd|_tjtj |_z |j|jSd|_XYnXdS)NF)rr decompressrrrr MAX_WBITS)rdataZ decompressedrrrr$ s"   zDeflateDecoder.decompressN)__name__ __module__ __qualname__r r#r$rrrrrsrc@s$eZdZddZddZddZdS) GzipDecodercCstjdtj|_dS)N)rrr%r)rrrrr 9szGzipDecoder.__init__cCs t|j|S)N)r!r)rr"rrrr#<szGzipDecoder.__getattr__cCs|s|S|jj|S)N)rr$)rr&rrrr$?szGzipDecoder.decompressN)r'r(r)r r#r$rrrrr*7sr*cCs|dkrtStS)Ngzip)r*r)moderrr _get_decoderEsr.c@seZdZdZddgZdddddgZdFddZddZddZe ddZ e ddZ ddZ ddZ ddZddZd d!Zed"d#ZdGd$d%ZdId(d)Zed*d+Zd,d-ZdJd.d/Zd0d1Zd2d3Ze d4d5Zd6d7Zd8d9Zd:d;Zdd?Z d@dAZ!dBdCZ"dKdDdEZ#d S)L HTTPResponsea  HTTP Response container. Backwards-compatible to httplib's 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 httplib.HTTPResponse: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, attempts to decode specific content-encoding's based on headers (like 'gzip' and 'deflate') will be skipped and raw data will be used instead. :param original_response: When this HTTPResponse wrapper is generated from an httplib.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. r,Zdeflatei-i.i/i3i4NrTFcCst|tr||_n t||_||_||_||_||_||_| |_| |_ d|_ d|_ d|_ | |_ d|_|r|t|ttfr|||_ | |_| |_t|dr||_ d|_d|_|jjddj}dd|jdD}d |krd |_|j||_|r|j r|j|d |_ dS) NrreadFztransfer-encodingr0css|]}|jVqdS)N)strip).0encrrr sz(HTTPResponse.__init__..,chunkedT)decode_content) isinstancerheadersstatusversionreasonstrictr8retriesenforce_content_length_decoder_body_fp_original_response_fp_bytes_read basestringr_pool _connectionhasattrr7 chunk_leftgetlowersplit _init_lengthlength_remainingr1)rbodyr:r;r<r=r>Zpreload_contentr8original_responseZpool connectionr?r@request_methodZtr_encZ encodingsrrrr qs<     zHTTPResponse.__init__cCs|j|jkr|jjdSdS)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)r;REDIRECT_STATUSESr:rK)rrrrget_redirect_locations  z"HTTPResponse.get_redirect_locationcCs,|j s|j rdS|jj|jd|_dS)N)rGrHZ _put_conn)rrrr release_connszHTTPResponse.release_conncCs"|jr |jS|jr|jddSdS)NT) cache_content)rBrCr1)rrrrr&szHTTPResponse.datacCs|jS)N)rH)rrrrrRszHTTPResponse.connectioncCs|jS)z Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). )rE)rrrrtellszHTTPResponse.tellcCs|jjd}|dk r(|jr(tjddS|dk rysz-HTTPResponse._init_length..r6rz8Content-Length contained multiple unmatching values (%s)r0dZHEAD)r]r^) r:rKr7logZwarningsetrMlenrpop ValueErrorrZr;)rrSZlengthZlengthsr;rrrrNs,      (zHTTPResponse._init_lengthcCs4|jjddj}|jdkr0||jkr0t||_dS)z= Set-up the _decoder attribute if necessary. zcontent-encodingr0N)r:rKrLrACONTENT_DECODERSr.)rcontent_encodingrrr _init_decoderszHTTPResponse._init_decodercCs|y|r|jr|jj|}WnHttjfk rb}z&|jjddj}td||WYdd}~XnX|rx|rx||j 7}|S)zN Decode the data passed in and potentially flush the decoder. zcontent-encodingr0zEReceived response with content-encoding: %s, but failed to decode it.N) rAr$IOErrorrrr:rKrLr _flush_decoder)rr&r8 flush_decoderergrrr_decodes  zHTTPResponse._decodecCs$|jr |jjd}||jjSdS)zk Flushes the decoder. Should only be called if the decoder is actually being used. )rAr$flush)rZbufrrrrjs zHTTPResponse._flush_decoderccsd}zy dVWntk r2t|jddYnptk rn}z"dt|krPt|jddWYdd}~Xn4ttfk r}ztd||WYdd}~XnXd}Wd|s|jr|jj |j r|j j |jr|jj r|j XdS)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) SocketTimeoutr rGrstrr SocketErrorr rDcloserHisclosedrW)rZ clean_exitrlrrr_error_catcher!s(      zHTTPResponse._error_catcherc Cs|j|dkr|j}|jdkr$dSd}d}|jh|dkrN|jj}d}nJd}|jj|}|dkr| r|jjd}|jr|jdkrt|j |jWdQRX|r|j t |7_ |jdk r|jt |8_|j |||}|r||_ |S)aP Similar to :meth:`httplib.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.) NFTr)rN) rhr8rCrur1rsr@rOr rErcrmrB)ramtr8rXrkr&rrrr1Zs4      zHTTPResponse.readr+ccsZ|jr.|jr.xF|j||dD] }|VqWn(x&t|jsT|j||d}|r0|Vq0WdS)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. )r8)rvr8N)r7supports_chunked_reads read_chunkedrrCr1)rrvr8liner&rrrstreams  zHTTPResponse.streamc Ks`|j}t|ts,tr"t|j}n tj|}t|dd}|f|||j|j|j ||d|}|S)a  Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. r>r)rPr:r;r<r=r>rQ) msgr9rritems from_httplibr!r;r<r=)Z ResponseClsrZ response_kwr:r>Zresprrrr~s    zHTTPResponse.from_httplibcCs|jS)N)r:)rrrr getheadersszHTTPResponse.getheaderscCs|jj||S)N)r:rK)rr"defaultrrr getheaderszHTTPResponse.getheadercCs|jS)N)r:)rrrrinfoszHTTPResponse.infocCs$|js|jj|jr |jjdS)N)closedrCrsrH)rrrrrss zHTTPResponse.closecCs@|jdkrdSt|jdr$|jjSt|jdr8|jjSdSdS)NTrtr)rCrIrtr)rrrrrs    zHTTPResponse.closedcCs6|jdkrtdnt|jdr*|jjStddS)Nz-HTTPResponse has no file to get a fileno fromfilenozOThe file-like object this HTTPResponse is wrapped around has no file descriptor)rCrirIr)rrrrrs     zHTTPResponse.filenocCs$|jdk r t|jdr |jjSdS)Nro)rCrIro)rrrrroszHTTPResponse.flushcCsdS)NTr)rrrrreadableszHTTPResponse.readablecCs:|jt|}t|dkrdS||dt|<t|SdS)Nr)r1rc)rbZtemprrrreadintos  zHTTPResponse.readintocCs t|jdS)z Checks if the underlying file-like object looks like a httplib.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)rIrC)rrrrrxsz#HTTPResponse.supports_chunked_readsc Csf|jdk rdS|jjj}|jddd}yt|d|_Wn&tk r`|jtj |YnXdS)N;rrr+) rJrCrreadlinerMrZrershttplibr )rrzrrr_update_chunk_lengths  z!HTTPResponse._update_chunk_lengthcCsd}|dkr2|jj|j}|}|jjdd|_nv||jkrZ|jj|}|j||_|}nN||jkr|jj|}|jjdd|_|}n |jj|j}|jjdd|_|S)Nrw)rCZ _safe_readrJ)rrvZreturned_chunkchunkvaluerrr _handle_chunk%s&        zHTTPResponse._handle_chunkc cs|j|jstd|js&td|jrDt|jrD|jjdS|jx<|j |j dkrdP|j |}|j ||dd}|rP|VqPW|r|j }|r|Vx |jjj}|sP|dkrPqW|jr|jjWdQRXdS)z Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :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.zgBody should be httplib.HTTPResponse like. It should have have an fp attribute which returns raw chunks.NrF)r8rks )rhr7r rxrrDrrsrurrJrrmrjrCrr)rrvr8rZdecodedrzrrrry;s@       zHTTPResponse.read_chunked)r0NrrNrTTNNNNFN)NNF)rN)N)NN)$r'r(r)__doc__rfrUr rVrWpropertyr&rRrYrNrhrmrjrrur1r{ classmethodr~rrrrsrrrorrrxrrryrrrrr/LsB  -  0  9 E       r/)-Z __future__r contextlibrrioZloggingZsocketrrprrr _collectionsr exceptionsrr r r r r rZ packages.sixrrFrrZpackages.six.movesrrrRrrZ util.responserrZ getLoggerr'raobjectrr*r.IOBaser/rrrrs"     $  !