a *Na+@sdZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZmZddlmZdd lmZdd lmZdd lmZdd lmZmZmZdd lmZmZmZm Z m!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/m0Z0m1Z1m2Z2ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?ddl3m@ZAddlBmCZCeCjDeCjEeCjFeCjGeCjHfZIdZJdZKdZLGdddeMZNGdddeMZOGdddeOZPGdddeNeOZQGdddeMZRdS) 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 InvalidURLChunkedEncodingErrorContentDecodingErrorConnectionErrorStreamConsumedErrorInvalidJSONError)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)selfr8pr9r;r?j/private/var/folders/js/6pj4vh5d4zd0k6bxv74qrbhr0000gr/T/pip-target-22xwyzbs/lib/python/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)doseq) isinstancer+r,hasattrrr0r:encoder*)dataresultkvsvr?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.rCNrDrB)namerIfilenameheaders) content_type) ValueErrorrFr0rrGr,r+r:decoderHtuplelistlenr bytearrayrBrmake_multipartr)filesrI new_fieldsfieldsfieldvalrMrKftfhfnfpfdatarfbodyrTr?r?r@ _encode_filesmsT                 z"RequestEncodingMixin._encode_filesN)__name__ __module__ __qualname__propertyrA staticmethodrNrhr?r?r?r@r4<s   r4c@seZdZddZddZdS)RequestHooksMixincCsZ||jvrtd|t|tr2|j||n$t|drV|j|dd|DdS)zProperly register a hook.z1Unsupported event specified, with event name "%s"rCcss|]}t|tr|VqdSN)rFr%).0hr?r?r@ z2RequestHooksMixin.register_hook..N)hooksrUrFr%r:rGextendr=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)rtremoverUrvr?r?r@deregister_hooks  z!RequestHooksMixin.deregister_hookN)rirjrkryr{r?r?r?r@rns rnc @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=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.) r~r8rSr\rIr1rrrrt) PreparedRequestpreparer~r8rSr\rIr1rrrrtr=r>r?r?r@rs zRequest.prepare) NNNNNNNNNN)rirjrk__doc__rrrr?r?r?r@r|s  r|c @seZdZdZddZdddZddZd d Zd d Ze d dZ ddZ ddZ dddZ ddZd ddZddZddZdS)!ra)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|_dSro)r~r8rS_cookiesrgr rt_body_positionrr?r?r@r%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=r~r8rSr\rIrrrrtr1r?r?r@r6s     zPreparedRequest.preparecCs d|jS)Nzrrr?r?r@rHszPreparedRequest.__repr__cCsXt}|j|_|j|_|jdur*|jnd|_t|j|_|j|_|j|_|j |_ |Sro) rr~r8rScopyrrrgrtrrr?r?r@rKs zPreparedRequest.copycCs$||_|jdur t|j|_dS)zPrepares the given HTTP method.N)r~rupper)r=r~r?r?r@rVs zPreparedRequest.prepare_methodcCs>ddl}z|j|ddd}Wn|jy8tYn0|S)NrT)uts46rD)idnarHrV 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:httpNzDInvalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?z Invalid URL %r: No host suppliedzURL has an invalid label.*r7@r5rDz%s&%s)rFr,rVr-unicoder+lstriplower startswithr8rrrargsformatrrrrrrHrNrr()r=r8rschemerrportr9r;fragmenteerrornetloc enc_paramsr?r?r@rfsh                   zPreparedRequest.prepare_urlcCs<t|_|r8|D]"}t||\}}||jt|<qdS)z Prepares the given HTTP headers.N)r rSr}r$r)r=rSheaderrQvaluer?r?r@rs  zPreparedRequest.prepare_headersc Csd}d}|sp|durpd}ztj|dd}Wn0tyZ}zt||dWYd}~n d}~00t|tsp|d}tt|dt|t t t t f g}|r8z t |}Wntttfyd}Yn0|}t|dddurz||_Wn ttfyt|_Yn0|rtd |r,t||jd <n d |jd <np|rP|||\}}n2|r||}t|t sxt|d r~d}nd}|||rd|jvr||jd<||_dS)z"Prepares the given HTTP body data.Nzapplication/jsonF) allow_nan)requestrDrCtellz1Streamed bodies and files are mutually exclusive.Content-LengthchunkedzTransfer-EncodingrBz!application/x-www-form-urlencodedz content-typez Content-Type) complexjsondumpsrUrrFr,rHallrGr0rXrWr&r# TypeErrorAttributeErrorr getattrrrIOErrorOSErrorobjectNotImplementedErrorr/rSrhrNprepare_content_lengthrg) r=rIr\r1rgrTve is_streamlengthr?r?r@rsR "        zPreparedRequest.prepare_bodycCsL|dur$t|}|rHt||jd<n$|jdvrH|jddurHd|jd<dS)z>Prepare Content-Length header based on request method and bodyNr)GETHEAD0)r#r/rSr~get)r=rgrr?r?r@rs z&PreparedRequest.prepare_content_lengthr7cCsj|dur"t|j}t|r|nd}|rft|trDt|dkrDt|}||}|j|j| |j dS)z"Prepares the given HTTP auth data.NrO) rr8anyrFrWrYr __dict__updaterrg)r=rr8url_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. NCookie)rFr' CookieJarrrrrS)r=r cookie_headerr?r?r@r4s   zPreparedRequest.prepare_cookiescCs&|pg}|D]}||||q dS)zPrepares the given hooks.N)ry)r=rtrwr?r?r@rHszPreparedRequest.prepare_hooks) NNNNNNNNNN)N)r7)rirjrkrrrrrrrmrrrrrrrrr?r?r?r@rs"   V J rc@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_coderSr8historyencodingreasonrelapsedrcCs^d|_d|_d|_d|_t|_d|_d|_d|_g|_ d|_ t i|_ t d|_d|_dS)NFr)r_content_consumed_nextrr rSrawr8rrrrrdatetime timedeltarrrr?r?r@r\s  zResponse.__init__cCs|Sror?rr?r?r@ __enter__szResponse.__enter__cGs |dSro)close)r=rr?r?r@__exit__szResponse.__exit__cs js jfddjDS)Ncsi|]}|t|dqSro)r)rpattrrr?r@ rsz)Response.__getstate__..)rcontent __attrs__rr?rr@ __getstate__szResponse.__getstate__cCs:|D]\}}t|||qt|ddt|dddS)NrTr)r}setattr)r=staterQrr?r?r@ __setstate__s zResponse.__setstate__cCs d|jS)Nz)rrr?r?r@rszResponse.__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``. okrr?r?r@__bool__szResponse.__bool__cCs|jSrrrr?r?r@ __nonzero__szResponse.__nonzero__cCs |dS)z,Allows you to use a response as an iterator.) iter_contentrr?r?r@rCszResponse.__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_statusrrr?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)rSrREDIRECT_STATIrr?r?r@ is_redirectszResponse.is_redirectcCsd|jvo|jtjtjfvS)z@True if this Response one of the permanent versions of redirect.r)rSrr2moved_permanentlypermanent_redirectrr?r?r@is_permanent_redirectszResponse.is_permanent_redirectcCs|jS)zTReturns a PreparedRequest for the next request in a redirect chain, if there is one.)rrr?r?r@nextsz Response.nextcCst|jdS)zOThe apparent encoding, provided by the charset_normalizer or chardet libraries.r)r.detectrrr?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)decode_content) rGrrrrrrrrrBr)chunkr chunk_sizer=r?r@generates    z'Response.iter_content..generateNz.chunk_size must be an int, it is instead a %s.) rrFrboolrintrtyper!r)r=rdecode_unicoder reused_chunks stream_chunkschunksr?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=rr 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 consumedrNrsT)rr RuntimeErrorrrr<rCONTENT_CHUNK_SIZErr?r?r@r7s 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 ``charset_normalizer`` or ``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. Nr7replace)errors)rrr+r LookupErrorr)r=rrr?r?r@textKs z Response.textcKsp|js\|jr\t|jdkr\t|j}|dur\ztj|j|fi|WStyZYn0tj|jfi|S)a.Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises simplejson.JSONDecodeError: If the response body does not contain valid json and simplejson is installed. :raises json.JSONDecodeError: If the response body does not contain valid json and simplejson is not installed on Python 3. :raises ValueError: If the response body does not contain valid json and simplejson is not installed on Python 2. rPN) rrrYr"rloadsrVUnicodeDecodeErrorr)r=kwargsrr?r?r@r1qs    z Response.jsoncCsF|jd}i}|rBt|}|D] }|dp6|d}|||<q |S)z8Returns the parsed header links of the response, if any.linkrelr8)rSrr )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.r7rDz iso-8859-1iiz%s Client Error: %s for url: %siXz%s Server Error: %s for url: %s)responseN)rFrr,rVrrr8r)r=http_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)rirjrkrrrrrrrrrrrCrlrrrrrrITER_CHUNK_SIZEr rrr1rrrr?r?r?r@rRs@/        7  % r)Srrsysencodings.idna encodingsZurllib3.fieldsrZurllib3.filepostrZ urllib3.utilrZurllib3.exceptionsrrrrior rtr structuresr rr rrrr exceptionsrrrrrrrr_internal_utilsrrutilsrrrrrr r!r"r#r$compatr%r&r'r(r)r*r+r,r-r.r/r0r1r status_codesr2movedfoundothertemporary_redirectrrDEFAULT_REDIRECT_LIMITr rrr4rnr|rrr?r?r?r@sD       (08  rJD