3 ¦˜‚]¢…ã@sÊdZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZmZddlmZdd lmZdd lmZdd lmZdd lmZmZmZdd lmZmZmZm Z m!Z!m"Z"m#Z#ddl$m%Z%m&Z&ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>ddl2m?Z@ddlAmBZBeBjCeBjDeBjEeBjFeBjGfZHdZId!ZJdZKGdd„deLƒZMGdd„deLƒZNGdd„deNƒZOGdd„deMeNƒZPGdd „d eLƒZQdS)"z` requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. éN)Ú RequestField)Úencode_multipart_formdata)Ú parse_url)Ú DecodeErrorÚReadTimeoutErrorÚ ProtocolErrorÚLocationParseError)ÚUnsupportedOperationé)Ú default_hooks)ÚCaseInsensitiveDict)Ú HTTPBasicAuth)Úcookiejar_from_dictÚget_cookie_headerÚ_copy_cookie_jar)Ú HTTPErrorÚ MissingSchemaÚ InvalidURLÚChunkedEncodingErrorÚContentDecodingErrorÚConnectionErrorÚStreamConsumedError)Úto_native_stringÚunicode_is_ascii) Úguess_filenameÚget_auth_from_urlÚ requote_uriÚstream_decode_response_unicodeÚto_key_val_listÚparse_header_linksÚ iter_slicesÚguess_json_utfÚ super_lenÚcheck_header_validity) ÚCallableÚMappingÚ cookielibÚ urlunparseÚurlsplitÚ urlencodeÚstrÚbytesÚis_py2ÚchardetÚ builtin_strÚ basestring)Újson)Úcodeséé iic@s0eZdZedd„ƒZedd„ƒZedd„ƒZdS)ÚRequestEncodingMixincCsNg}t|jƒ}|j}|sd}|j|ƒ|j}|rD|jdƒ|j|ƒdj|ƒS)zBuild the path URL to use.ú/ú?Ú)r(ÚurlÚpathÚappendÚqueryÚjoin)Úselfr8Úpr9r;©r?ú3/tmp/pip-build-el9acr48/requests/requests/models.pyÚpath_url=s    zRequestEncodingMixin.path_urlcCsÀt|ttfƒr|St|dƒr |St|dƒr¸g}x|t|ƒD]p\}}t|tƒsVt|dƒ r\|g}xJ|D]B}|dk rb|jt|tƒr†|jdƒn|t|tƒrœ|jdƒn|fƒqbWq8Wt|dd�S|SdS)züEncode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. ÚreadÚ__iter__Nzutf-8T)Údoseq) Ú isinstancer*r+Úhasattrrr/r:Úencoder))ÚdataÚresultÚkÚvsÚvr?r?r@Ú_encode_paramsRs    $ z#RequestEncodingMixin._encode_paramscCs¾|stdƒ‚nt|tƒr tdƒ‚g}t|p,iƒ}t|p8iƒ}xŠ|D]‚\}}t|tƒs`t|dƒ rf|g}x\|D]T}|dk rlt|tƒsŠt|ƒ}|jt|tƒr¢|jdƒn|t|tƒr¸|j dƒn|fƒqlWqBWxà|D]Ø\}}d}d} t|t t fƒ�r.t |ƒdk�r|\} } n&t |ƒdk�r |\} } }n |\} } }} nt |ƒ�p:|} |} t| tttfƒ�rX| } n(t| dƒ�rn| jƒ} n| dk�r|qÎn| } t|| | | d �} | j|d �|j| ƒqÎWt|ƒ\}}||fS) a¥Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). zFiles must be provided.zData must not be a string.rCNzutf-8éérB)ÚnamerHÚfilenameÚheaders)Ú content_type)Ú ValueErrorrEr/rrFr+r*r:ÚdecoderGÚtupleÚlistÚlenrÚ bytearrayrBrÚmake_multipartr)ÚfilesrHÚ new_fieldsÚfieldsÚfieldÚvalrLrJÚftÚfhÚfnÚfpÚfdataÚrfÚbodyrSr?r?r@Ú _encode_filesmsP       $       z"RequestEncodingMixin._encode_filesN)Ú__name__Ú __module__Ú __qualname__ÚpropertyrAÚ staticmethodrMrgr?r?r?r@r4<s  r4c@seZdZdd„Zdd„ZdS)ÚRequestHooksMixincCsZ||jkrtd|ƒ‚t|tƒr2|j|j|ƒn$t|dƒrV|j|jdd„|DƒƒdS)zProperly register a hook.z1Unsupported event specified, with event name "%s"rCcss|]}t|tƒr|VqdS)N)rEr$)Ú.0Úhr?r?r@ú ¸sz2RequestHooksMixin.register_hook..N)ÚhooksrTrEr$r:rFÚextend)r=ÚeventÚhookr?r?r@Ú register_hook¯s     zRequestHooksMixin.register_hookc Cs.y|j|j|ƒdStk r(dSXdS)ziDeregister a previously registered hook. Returns True if the hook existed, False if not. TFN)rqÚremoverT)r=rsrtr?r?r@Úderegister_hookºs z!RequestHooksMixin.deregister_hookN)rhrirjrurwr?r?r?r@rm®s rmc @s*eZdZdZd dd„Zdd„Zdd„ZdS) ÚRequesta{A user-created :class:`Request ` object. Used to prepare a :class:`PreparedRequest `, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param json: json for the body to attach to the request (if files or data is not specified). :param params: URL parameters to append to the URL. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() Nc Csº|dkr gn|}|dkrgn|}|dkr,in|}|dkr)rz)r=r?r?r@Ú__repr__ûszRequest.__repr__c Cs<tƒ}|j|j|j|j|j|j|j|j|j |j |j d� |S)zXConstructs a :class:`PreparedRequest ` for transmission and returns it.) rzr8rRr[rHr0r{r|r}rq) ÚPreparedRequestÚpreparerzr8rRr[rHr0r{r|r}rq)r=r>r?r?r@r�þs zRequest.prepare) NNNNNNNNNN)rhrirjÚ__doc__r~rr�r?r?r?r@rxÆs  rxc @s‚eZdZdZdd„Zddd„Zdd„Zd d „Zd d „Ze d d„ƒZ dd„Z dd„Z ddd„Z dd„Zd dd„Zdd„Zdd„ZdS)!r€aÇThe fully mutable :class:`PreparedRequest ` object, containing the exact bytes that will be sent to the server. Generated from either a :class:`Request ` object or manually. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() >>> s = requests.Session() >>> s.send(r) cCs0d|_d|_d|_d|_d|_tƒ|_d|_dS)N)rzr8rRÚ_cookiesrfr rqÚ_body_position)r=r?r?r@r~"szPreparedRequest.__init__Nc CsR|j|ƒ|j||ƒ|j|ƒ|j|ƒ|j||| ƒ|j||ƒ|j| ƒdS)z6Prepares the entire request with the given parameters.N)Úprepare_methodÚ prepare_urlÚprepare_headersÚprepare_cookiesÚ prepare_bodyÚ prepare_authÚ prepare_hooks) r=rzr8rRr[rHr{r|r}rqr0r?r?r@r�3s     zPreparedRequest.preparecCs d|jS)Nz)rz)r=r?r?r@rEszPreparedRequest.__repr__cCsXtƒ}|j|_|j|_|jdk r*|jjƒnd|_t|jƒ|_|j|_|j|_|j |_ |S)N) r€rzr8rRÚcopyrrƒrfrqr„)r=r>r?r?r@rŒHs zPreparedRequest.copycCs$||_|jdk r t|jjƒƒ|_dS)zPrepares the given HTTP method.N)rzrÚupper)r=rzr?r?r@r…Ss zPreparedRequest.prepare_methodc Cs@ddl}y|j|dd�jdƒ}Wn|jk r:t‚YnX|S)NrT)Úuts46zutf-8)ÚidnarGrUÚ IDNAErrorÚ UnicodeError)Úhostr�r?r?r@Ú_get_idna_encoded_hostYs  z&PreparedRequest._get_idna_encoded_hostcCs0t|tƒr|jdƒ}ntr"t|ƒnt|ƒ}|jƒ}d|krT|jƒjdƒ rT||_ dSyt |ƒ\}}}}}}} Wn,t k rš} zt | j Ž‚WYdd} ~ XnX|s¼d} | jt|dƒƒ} t| ƒ‚|sÌt d|ƒ‚t|ƒ�sy|j|ƒ}Wntk �rt dƒ‚YnXn|jdƒ�rt dƒ‚|�p"d } | �r2| d 7} | |7} |�rP| dt|ƒ7} |�sZd }t�rÎt|tƒ�rv|jd ƒ}t| tƒ�rŒ| jd ƒ} t|tƒ�r¢|jd ƒ}t|tƒ�r¸|jd ƒ}t| tƒ�rÎ| jd ƒ} t|ttfƒ�ræt|ƒ}|j|ƒ} | �r|�r d || f}n| }tt|| |d|| gƒƒ}||_ dS)zPrepares the given HTTP URL.Úutf8ú:ÚhttpNzDInvalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?z Invalid URL %r: No host suppliedzURL has an invalid label.Ú*r7ú@r5zutf-8z%s&%s)rEr+rUr,Úunicoder*ÚlstripÚlowerÚ startswithr8rrrÚargsÚformatrrrr“r‘rGrMrr')r=r8r{Úschemer|r’Úportr9r;ÚfragmentÚeÚerrorÚnetlocÚ enc_paramsr?r?r@r†csh                 zPreparedRequest.prepare_urlcCs@tƒ|_|rPrepare Content-Length header based on request method and bodyNzContent-LengthÚGETÚHEADÚ0)r·r¸)r"r.rRrzÚget)r=rfr¶r?r?r@r´ s z&PreparedRequest.prepare_content_lengthr7cCsj|dkr"t|jƒ}t|ƒr|nd}|rft|tƒrDt|ƒdkrDt|Ž}||ƒ}|jj|jƒ|j |j ƒdS)z"Prepares the given HTTP auth data.NrN) rr8ÚanyrErVrXr Ú__dict__Úupdater´rf)r=r|r8Úurl_authÚrr?r?r@rŠs zPreparedRequest.prepare_authcCs@t|tjƒr||_n t|ƒ|_t|j|ƒ}|dk r<||jd<dS)aPrepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest ` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand. NÚCookie)rEr&Ú CookieJarrƒrrrR)r=r}Ú cookie_headerr?r?r@rˆ,s   zPreparedRequest.prepare_cookiescCs*|pg}x|D]}|j|||ƒqWdS)zPrepares the given hooks.N)ru)r=rqrsr?r?r@r‹@s zPreparedRequest.prepare_hooks) NNNNNNNNNN)N)r7)rhrirjr‚r~r�rrŒr…rlr“r†r‡r‰r´rŠrˆr‹r?r?r?r@r€s   V E r€c @seZdZdZdddddddd d d g Zd d „Zdd„Zdd„Zdd„Zdd„Z dd„Z dd„Z dd„Z dd„Z edd„ƒZed d!„ƒZed"d#„ƒZed$d%„ƒZed&d'„ƒZd;d*d+„Zed)d,fd-d.„Zed/d0„ƒZed1d2„ƒZd3d4„Zed5d6„ƒZd7d8„Zd9d:„Zd,S)<ÚResponsezhThe :class:`Response ` object, which contains a server's response to an HTTP request. Ú_contentÚ status_coderRr8ÚhistoryÚencodingÚreasonr}ÚelapsedÚrequestcCs^d|_d|_d|_d|_tƒ|_d|_d|_d|_g|_ d|_ t iƒ|_ t jdƒ|_d|_dS)NFr)rÄÚ_content_consumedÚ_nextrÅr rRÚrawr8rÇrÆrÈrr}ÚdatetimeÚ timedeltarÉrÊ)r=r?r?r@r~Ts  zResponse.__init__cCs|S)Nr?)r=r?r?r@Ú __enter__ƒszResponse.__enter__cGs |jƒdS)N)Úclose)r=r�r?r?r@Ú__exit__†szResponse.__exit__cs ˆjs ˆj‡fdd„ˆjDƒS)Ncsi|]}tˆ|dƒ|“qS)N)r¯)rnÚattr)r=r?r@ú �sz)Response.__getstate__..)rËÚcontentÚ __attrs__)r=r?)r=r@Ú __getstate__‰szResponse.__getstate__cCs>x |jƒD]\}}t|||ƒq Wt|ddƒt|ddƒdS)NrËTrÍ)ryÚsetattr)r=ÚstaterPr§r?r?r@Ú __setstate__‘s zResponse.__setstate__cCs d|jS)Nz)rÅ)r=r?r?r@r™szResponse.__repr__cCs|jS)akReturns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. )Úok)r=r?r?r@Ú__bool__œszResponse.__bool__cCs|jS)akReturns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. )rÛ)r=r?r?r@Ú __nonzero__¦szResponse.__nonzero__cCs |jdƒS)z,Allows you to use a response as an iterator.é€)Ú iter_content)r=r?r?r@rC°szResponse.__iter__c Cs&y |jƒWntk r dSXdS)axReturns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. FT)Úraise_for_statusr)r=r?r?r@rÛ´s  z Response.okcCsd|jko|jtkS)zšTrue if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). Úlocation)rRrÅÚREDIRECT_STATI)r=r?r?r@Ú is_redirectÃszResponse.is_redirectcCsd|jko|jtjtjfkS)z@True if this Response one of the permanent versions of redirect.rá)rRrÅr1Úmoved_permanentlyÚpermanent_redirect)r=r?r?r@Úis_permanent_redirectÊszResponse.is_permanent_redirectcCs|jS)zTReturns a PreparedRequest for the next request in a redirect chain, if there is one.)rÌ)r=r?r?r@ÚnextÏsz Response.nextcCstj|jƒdS)z7The apparent encoding, provided by the chardet library.rÇ)r-ÚdetectrÕ)r=r?r?r@Úapparent_encodingÔszResponse.apparent_encodingr Fcs~‡‡fdd„}ˆjr(tˆjtƒr(tƒ‚n$ˆdk rLtˆtƒ rLtdtˆƒƒ‚tˆjˆƒ}|ƒ}ˆjrh|n|}|rzt |ˆƒ}|S)aøIterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response. c3sÖtˆjdƒr®y$xˆjjˆdd�D] }|Vq WWqÌtk rZ}zt|ƒ‚WYdd}~XqÌtk r‚}zt|ƒ‚WYdd}~XqÌtk rª}zt|ƒ‚WYdd}~XqÌXnxˆjj ˆƒ}|sÂP|Vq°Wdˆ_ dS)NÚstreamT)Údecode_content) rFrÍrêrrrrrrrBrË)Úchunkr¢)Ú chunk_sizer=r?r@Úgenerateês    z'Response.iter_content..generateNz.chunk_size must be an int, it is instead a %s.) rËrErÄÚboolrÚintr­Útyper r)r=ríÚdecode_unicoderîÚ reused_chunksÚ stream_chunksÚchunksr?)rír=r@rßÙs  zResponse.iter_contentNccsœd}x„|j||d�D]r}|dk r(||}|r8|j|ƒ}n|jƒ}|rn|drn|rn|dd|dkrn|jƒ}nd}x|D] }|VqxWqW|dk r˜|VdS)zõIterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. N)ríròr éÿÿÿÿrörörö)rßÚsplitÚ splitlinesÚpop)r=ríròÚ delimiterÚpendingrìÚlinesÚliner?r?r@Ú iter_liness $  zResponse.iter_linescCsV|jdkrJ|jrtdƒ‚|jdks,|jdkr4d|_ndj|jtƒƒpFd|_d|_|jS)z"Content of the response, in bytes.Fz2The content for this response was already consumedrNóT)rÄrËÚ RuntimeErrorrÅrÍr<rßÚCONTENT_CHUNK_SIZE)r=r?r?r@rÕ/s zResponse.contentc Cshd}|j}|jstdƒS|jdkr(|j}yt|j|dd�}Wn&ttfk rbt|jdd�}YnX|S)aÀContent of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. Nr7Úreplace)Úerrors)rÇrÕr*réÚ LookupErrorr­)r=rÕrÇr?r?r@ÚtextCs z Response.textc Ksj|j rZ|jrZt|jƒdkrZt|jƒ}|dk rZytj|jj|ƒf|ŽStk rXYnXtj|jf|ŽS)zØReturns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. rON) rÇrÕrXr!rªÚloadsrUÚUnicodeDecodeErrorr)r=ÚkwargsrÇr?r?r@r0is z Response.jsoncCsJ|jjdƒ}i}|rFt|ƒ}x(|D] }|jdƒp8|jdƒ}|||<q"W|S)z8Returns the parsed header links of the response, if any.ÚlinkÚrelr8)rRrºr)r=r¦ÚlÚlinksr Úkeyr?r?r@r ƒs   zResponse.linksc Cs¸d}t|jtƒrDy|jjdƒ}WqJtk r@|jjdƒ}YqJXn|j}d|jko^dknrxd|j||jf}n,d|jkoŒdknr¤d|j||jf}|r´t||d �‚d S) z2Raises stored :class:`HTTPError`, if one occurred.r7zutf-8z iso-8859-1i�iôz%s Client Error: %s for url: %siXz%s Server Error: %s for url: %s)ÚresponseN)rErÈr+rUrrÅr8r)r=Úhttp_error_msgrÈr?r?r@rà•s zResponse.raise_for_statuscCs0|js|jjƒt|jddƒ}|dk r,|ƒdS)zØReleases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* Ú release_connN)rËrÍrÑr¯)r=rr?r?r@rÑ®s  zResponse.close)r F)rhrirjr‚rÖr~rÐrÒr×rÚrrÜrÝrCrkrÛrãrærçrérßÚITER_CHUNK_SIZErþrÕrr0r ràrÑr?r?r?r@rÃJs2 /        7  & rÃi()Rr‚rÎÚsysÚencodings.idnaÚ encodingsZurllib3.fieldsrZurllib3.filepostrZ urllib3.utilrZurllib3.exceptionsrrrrÚior rqr Ú structuresr r|r r}rrrÚ exceptionsrrrrrrrÚ_internal_utilsrrÚutilsrrrrrrr r!r"r#Úcompatr$r%r&r'r(r)r*r+r,r-r.r/r0rªÚ status_codesr1ÚmovedÚfoundÚotherÚtemporary_redirectrårâÚDEFAULT_REDIRECT_LIMITrrr²r4rmrxr€rÃr?r?r?r@ÚsB       $08  rJ<