a Ba_@sdZddlZddlZddlZddlmZddlmZddl 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@ddlAmBZBeBjCeBjDeBjEeBjFeBjGfZHdZIdZJdZKGdddeLZMGdddeLZNGdddeNZOGdddeMeNZPGdddeLZQdS) z` requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. N) RequestField)encode_multipart_formdata) parse_url) DecodeErrorReadTimeoutError ProtocolErrorLocationParseError)UnsupportedOperation) default_hooks)CaseInsensitiveDict) HTTPBasicAuth)cookiejar_from_dictget_cookie_header_copy_cookie_jar) HTTPError MissingSchema InvalidURLChunkedEncodingErrorContentDecodingErrorConnectionErrorStreamConsumedError)to_native_stringunicode_is_ascii) guess_filenameget_auth_from_url requote_uristream_decode_response_unicodeto_key_val_listparse_header_links iter_slicesguess_json_utf super_lencheck_header_validity) CallableMapping cookielib urlunparseurlsplit urlencodestrbytesis_py2chardet builtin_str basestring)json)codesi(ic@s0eZdZeddZeddZeddZdS)RequestEncodingMixincCsNg}t|j}|j}|sd}|||j}|rD|d||d|S)zBuild the path URL to use./?)r(urlpathappendqueryjoin)selfr7pr8r:r>1/usr/lib/python3/dist-packages/requests/models.pypath_url=s    zRequestEncodingMixin.path_urlcCst|ttfr|St|dr |St|drg}t|D]j\}}t|tsRt|dsX|g}|D]B}|dur\|t|tr|dn|t|tr|dn|fq\q6t|ddS|SdS)zEncode 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__Nutf-8T)Zdoseq) isinstancer*r+hasattrrr/r9encoder))dataresultkZvsvr>r>r?_encode_paramsRs$    z#RequestEncodingMixin._encode_paramscCs|stdnt|tr tdg}t|p,i}t|p8i}|D]|\}}t|ts\t|dsb|g}|D]T}|durft|tst|}|t|tr|dn|t|tr| dn|fqfq@|D]\}}d}d} t|t t fr t |dkr|\} } n&t |dkr|\} } }n |\} } }} nt |p,|} |} t| tttfrJ| } n(t| dr`| } n| durnqn| } t|| | | d } | j|d || qt|\}}||fS) aBuild 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.rBNrCrA)namerGfilenameheaders) content_type) ValueErrorrDr/rrEr+r*r9decoderFtuplelistlenr bytearrayrArZmake_multipartr)filesrGZ new_fieldsfieldsZfieldvalrJrIZftZfhfnfpZfdataZrfbodyrQr>r>r? _encode_filesmsT                 z"RequestEncodingMixin._encode_filesN)__name__ __module__ __qualname__propertyr@ staticmethodrKr^r>r>r>r?r3<s   r3c@seZdZddZddZdS)RequestHooksMixincCsZ||jvrtd|t|tr2|j||n$t|drV|j|dd|DdS)zProperly register a hook.z1Unsupported event specified, with event name "%s"rBcss|]}t|tr|VqdSN)rDr$).0hr>r>r? z2RequestHooksMixin.register_hook..N)hooksrRrDr$r9rEextendr<eventhookr>r>r? register_hooks     zRequestHooksMixin.register_hookcCs0z|j||WdSty*YdS0dS)ziDeregister a previously registered hook. Returns True if the hook existed, False if not. TFN)rjremoverRrlr>r>r?deregister_hooks  z!RequestHooksMixin.deregister_hookN)r_r`rarorqr>r>r>r?rds rdc @s*eZdZdZd ddZddZddZdS) 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|dur gn|}|durgn|}|dur,in|}|durr>r?__init__s"zRequest.__init__cCs d|jS)Nzrtr<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.) rtr7rPrXrGr0rurvrwrj) PreparedRequestpreparertr7rPrXrGr0rurvrwrjr<r=r>r>r?r}s zRequest.prepare) NNNNNNNNNN)r_r`ra__doc__rxr{r}r>r>r>r?rrs  rrc @seZdZdZddZdddZddZd d Zd d Ze d dZ ddZ ddZ dddZ ddZd ddZddZddZdS)!r|a)The fully mutable :class:`PreparedRequest ` object, containing the exact bytes that will be sent to the server. Instances are generated from a :class:`Request ` object, and should not be instantiated manually; doing so may produce undesirable effects. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() >>> r >>> s = requests.Session() >>> s.send(r) cCs0d|_d|_d|_d|_d|_t|_d|_dSre)rtr7rP_cookiesr]r rj_body_positionrzr>r>r?rx%szPreparedRequest.__init__Nc CsR||||||||||||| ||||| dS)z6Prepares the entire request with the given parameters.N)prepare_method prepare_urlprepare_headersprepare_cookies prepare_body prepare_auth prepare_hooks) r<rtr7rPrXrGrurvrwrjr0r>r>r?r}6s     zPreparedRequest.preparecCs d|jS)Nzryrzr>r>r?r{HszPreparedRequest.__repr__cCsXt}|j|_|j|_|jdur*|jnd|_t|j|_|j|_|j|_|j |_ |Sre) r|rtr7rPcopyrrr]rjrr~r>r>r?rKs zPreparedRequest.copycCs$||_|jdur t|j|_dS)zPrepares the given HTTP method.N)rtrupper)r<rtr>r>r?rVs zPreparedRequest.prepare_methodcCs>ddl}z|j|ddd}Wn|jy8tYn0|S)NrT)Zuts46rC)idnarFrSZ IDNAError UnicodeError)hostrr>r>r?_get_idna_encoded_host\s  z&PreparedRequest._get_idna_encoded_hostc Cs,t|tr|d}ntr"t|nt|}|}d|vrR|dsR||_ dSzt |\}}}}}}} Wn.t y} zt | j WYd} ~ n d} ~ 00|sd} | t|d} t| |st d|t|sz||}Wntyt dYn0n|drt d|pd } | r.| d 7} | |7} |rL| dt|7} |sVd }trt|trr|d }t| tr| d } t|tr|d }t|tr|d }t| tr| d } t|ttfrt|}||} | r |rd || f}n| }tt|| |d|| g}||_ dS)zPrepares the given HTTP URL.utf8:ZhttpNzDInvalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?z Invalid URL %r: No host suppliedzURL has an invalid label.*r6@r4rCz%s&%s)rDr+rSr,Zunicoder*lstriplower startswithr7rrrargsformatrrrrrrFrKrr')r<r7ruZschemervrZportr8r:ZfragmenteerrorZnetlocZ enc_paramsr>r>r?rfsh                   zPreparedRequest.prepare_urlcCs<t|_|r8|D]"}t||\}}||jt|<qdS)z Prepares the given HTTP headers.N)r rPrsr#r)r<rPheaderrNvaluer>r>r?rs  zPreparedRequest.prepare_headersc Csnd}d}|s6|dur6d}t|}t|ts6|d}tt|dt|ttt t f g}|rz t |}Wnt t tfyd}Yn0|}t|dddurz||_Wnttfyt|_Yn0|rtd|rt||jd<n d|jd <np|r |||\}}n2|r>||}t|ts4t|d r:d}nd }|||rdd |jvrd||jd <||_dS)z"Prepares the given HTTP body data.Nzapplication/jsonrCrBtellz1Streamed bodies and files are mutually exclusive.Content-LengthZchunkedzTransfer-EncodingrAz!application/x-www-form-urlencodedz content-typez Content-Type) complexjsondumpsrDr+rFallrEr/rUrTr%r" TypeErrorAttributeErrorr getattrrrIOErrorOSErrorobjectNotImplementedErrorr.rPr^rKprepare_content_lengthr])r<rGrXr0r]rQZ is_streamlengthr>r>r?rsL          zPreparedRequest.prepare_bodycCsL|dur$t|}|rHt||jd<n$|jdvrH|jddurHd|jd<dS)z>Prepare Content-Length header based on request method and bodyNr)ZGETZHEAD0)r"r.rPrtget)r<r]rr>r>r?r s z&PreparedRequest.prepare_content_lengthr6cCsj|dur"t|j}t|r|nd}|rft|trDt|dkrDt|}||}|j|j| |j dS)z"Prepares the given HTTP auth data.NrL) rr7anyrDrTrVr __dict__updaterr])r<rvr7Zurl_authrr>r>r?rs zPreparedRequest.prepare_authcCs@t|tjr||_n t||_t|j|}|dur<||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. NZCookie)rDr&Z CookieJarrrrrP)r<rwZ cookie_headerr>r>r?r/s   zPreparedRequest.prepare_cookiescCs&|pg}|D]}||||q dS)zPrepares the given hooks.N)ro)r<rjrmr>r>r?rCszPreparedRequest.prepare_hooks) NNNNNNNNNN)N)r6)r_r`rarrxr}r{rrrcrrrrrrrrr>r>r>r?r|s"   V E r|c@seZdZdZgdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ eddZeddZeddZeddZeddZd2d!d"Zed d#fd$d%Zed&d'Zed(d)Zd*d+Zed,d-Zd.d/Zd0d1Zd#S)3ResponsezhThe :class:`Response ` object, which contains a server's response to an HTTP request. ) _content status_coderPr7historyencodingreasonrwelapsedrequestcCs^d|_d|_d|_d|_t|_d|_d|_d|_g|_ d|_ t i|_ t d|_d|_dS)NFr)r_content_consumed_nextrr rPrawr7rrrrrwdatetimeZ timedeltarrrzr>r>r?rxWs  zResponse.__init__cCs|Srer>rzr>r>r? __enter__szResponse.__enter__cGs |dSre)close)r<rr>r>r?__exit__szResponse.__exit__cs js jfddjDS)Ncsi|]}|t|dqSre)r)rfattrrzr>r? riz)Response.__getstate__..)rcontent __attrs__rzr>rzr? __getstate__szResponse.__getstate__cCs:|D]\}}t|||qt|ddt|dddS)NrTr)rssetattr)r<staterNrr>r>r? __setstate__s zResponse.__setstate__cCs d|jS)Nz)rrzr>r>r?r{szResponse.__repr__cCs|jSakReturns 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``. okrzr>r>r?__bool__szResponse.__bool__cCs|jSrrrzr>r>r? __nonzero__szResponse.__nonzero__cCs |dS)z,Allows you to use a response as an iterator.) iter_contentrzr>r>r?rBszResponse.__iter__cCs&z |Wnty YdS0dS)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_statusrrzr>r>r?rs   z Response.okcCsd|jvo|jtvS)zTrue if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). location)rPrREDIRECT_STATIrzr>r>r? is_redirectszResponse.is_redirectcCsd|jvo|jtjtjfvS)z@True if this Response one of the permanent versions of redirect.r)rPrr1Zmoved_permanentlypermanent_redirectrzr>r>r?is_permanent_redirectszResponse.is_permanent_redirectcCs|jS)zTReturns a PreparedRequest for the next request in a redirect chain, if there is one.)rrzr>r>r?nextsz Response.nextcCst|jdS)z7The apparent encoding, provided by the chardet library.r)r-Zdetectrrzr>r>r?apparent_encodingszResponse.apparent_encodingr Fcs|fdd}jr(tjtr(tn"durJttsJtdttj}|}jrf|n|}|rxt |}|S)aIterates 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. c 3stjdrz jjddD] }|VqWqtyX}zt|WYd}~qd}~0ty}zt|WYd}~qd}~0ty}zt|WYd}~qd}~00nj }|sq|Vqd_ dS)NstreamT)Zdecode_content) rErrrrrrrrrAr)chunkr chunk_sizer<r>r?generates    z'Response.iter_content..generateNz.chunk_size must be an int, it is instead a %s.) rrDrboolrintrtyper r)r<rdecode_unicoderZ reused_chunksZ stream_chunksZchunksr>rr?rs  zResponse.iter_contentNccsd}|j||dD]n}|dur&||}|r6||}n|}|rl|drl|rl|dd|dkrl|}nd}|D] }|Vqtq|dur|VdS)zIterates 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)rr)rsplit splitlinespop)r<rrZ delimiterpendingrlinesliner>r>r? iter_liness $  zResponse.iter_linescCsV|jdurJ|jrtd|jdks,|jdur4d|_nd|tpFd|_d|_|jS)z"Content of the response, in bytes.Fz2The content for this response was already consumedrNriT)rr RuntimeErrorrrr;rCONTENT_CHUNK_SIZErzr>r>r?r2s zResponse.contentc Csfd}|j}|jstdS|jdur(|j}zt|j|dd}Wn$ttfy`t|jdd}Yn0|S)aContent 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. Nr6replace)errors)rrr*r LookupErrorr)r<rrr>r>r?textFs z Response.textcKsp|js\|jr\t|jdkr\t|j}|dur\ztj|j|fi|WStyZYn0tj|jfi|S)zReturns 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. rMN) rrrVr!rloadsrSUnicodeDecodeErrorr)r<kwargsrr>r>r?r0ls   z Response.jsoncCsF|jd}i}|rBt|}|D] }|dp6|d}|||<q |S)z8Returns the parsed header links of the response, if any.linkZrelr7)rPrr)r<rllinksrkeyr>r>r?rs  zResponse.linkscCsd}t|jtrBz|jd}WqHty>|jd}YqH0n|j}d|jkr^dkrvnnd|j||jf}n,d|jkrdkrnnd|j||jf}|rt||d d S) z+Raises :class:`HTTPError`, if one occurred.r6rCz iso-8859-1iiz%s Client Error: %s for url: %siXz%s Server Error: %s for url: %s)ZresponseN)rDrr+rSrrr7r)r<Zhttp_error_msgrr>r>r?rs  zResponse.raise_for_statuscCs0|js|jt|jdd}|dur,|dS)zReleases 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)rrrr)r<rr>r>r?rs  zResponse.close)r F)r_r`rarrrxrrrrr{rrrBrbrrrrrrITER_CHUNK_SIZErrrr0rrrr>r>r>r?rMs@/        7  % r)RrrsysZencodings.idnaZ encodingsZurllib3.fieldsrZurllib3.filepostrZ urllib3.utilrZurllib3.exceptionsrrrrior rjr Z structuresr rvr rwrrr exceptionsrrrrrrrZ_internal_utilsrrZutilsrrrrrrr r!r"r#compatr$r%r&r'r(r)r*r+r,r-r.r/r0rZ status_codesr1ZmovedfoundotherZtemporary_redirectrrZDEFAULT_REDIRECT_LIMITrrrr3rdrrr|rr>r>r>r?sD       $08  rJ?