ReDg@s;dZddlZddlZddlmZmZddlmZddlm Z ddl m Z ddl m Z mZdd lmZdd lmZdd lmZdd lmZdd lmZmZmZmZmZmZddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8e8j9e8j:e8j;e8j<fZ=dZ>dZ?dZ@GdddeAZBGdddeAZCGdddeCZDGdddeBeCZEGdddeAZFdS) z` requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. N)BytesIOUnsupportedOperation) default_hooks)CaseInsensitiveDict) HTTPBasicAuth)cookiejar_from_dictget_cookie_header) RequestField)encode_multipart_formdata) parse_url) DecodeError) HTTPErrorRequestException MissingSchema InvalidURLChunkedEncodingErrorContentDecodingError) guess_filenameget_auth_from_url requote_uristream_decode_response_unicodeto_key_val_listparse_header_links iter_slicesguess_json_utf super_lento_native_string) cookielib urlunparseurlsplit urlencodestrbytesStringIOis_py2chardetjson builtin_str basestringIncompleteRead)codes iic@sFeZdZeddZeddZeddZdS)RequestEncodingMixincCssg}t|j}|j}|s-d}n|j||j}|rf|jd|j|ndj|S)zBuild the path URL to use./?)r urlpathappendqueryjoin)selfr2pr3r5r96/tmp/pip-ztkk0jow-build/pip/_vendor/requests/models.pypath_url1s     zRequestEncodingMixin.path_urlcCst|ttfr|St|dr,|St|drg}xt|D]\}}t|tsyt|d r|g}nxl|D]d}|dk r|jt|tr|jdn|t|tr|jdn|fqqWqNWt|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__Nzutf-8doseqT) isinstancer"r#hasattrrr)r4encoder!)dataresultkvsvr9r9r:_encode_paramsFs    !3z#RequestEncodingMixin._encode_paramsc Csr|stdnt|tr3tdng}t|pEi}t|pWi}x|D]\}}t|tst|d r|g}nx|D]}|dk rt|tst|}n|jt|tr|jdn|t|tr|j dn|fqqWqdWx'|D]\}}d}d} t|t t frt |dkr|\} } qt |dkr|\} } }q|\} } }} nt |p|} |} t| trt| } nt| trt| } ntd|d | jd | d | } | jd ||j| q3Wt|\} }| |fS) aBuild the body for a multipart/form-data request. Will successfully encode files 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. zFiles must be provided.zData must not be a string.r=Nzutf-8namerBfilenameheaders content_type) ValueErrorr?r)rr@r#r"r4decoderAtuplelistlenrr$rr r<make_multipartr )filesrB new_fieldsfieldsfieldvalrFrDftfhfnfprfbodyrMr9r9r: _encode_filesasL    !3z"RequestEncodingMixin._encode_filesN)__name__ __module__ __qualname__propertyr; staticmethodrGr_r9r9r9r:r.0s r.c@s(eZdZddZddZdS)RequestHooksMixincCs||jkr"td|nt|tjrK|j|j|n3t|dr~|j|jdd|DndS)zProperly register a hook.z1Unsupported event specified, with event name "%s"r=css'|]}t|tjr|VqdS)N)r? collectionsCallable).0hr9r9r: sz2RequestHooksMixin.register_hook..N)hooksrNr?rfrgr4r@extend)r7eventhookr9r9r: register_hooks zRequestHooksMixin.register_hookc Cs9y|j|j|dSWntk r4dSYnXdS)ziDeregister a previously registered hook. Returns True if the hook existed, False if not. TFN)rkremoverN)r7rmrnr9r9r:deregister_hooks  z!RequestHooksMixin.deregister_hookN)r`rarbrorqr9r9r9r:res  rec @sUeZdZdZddddddddddd ZddZddZdS) RequestaA 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 the request. If a dictionary is provided, form-encoding will take place. :param params: dictionary of URL parameters to append to the URL. :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', 'http://httpbin.org/get') >>> req.prepare() Nc Cs |dkrgn|}|dkr*gn|}|dkrBin|}|dkrZin|}| dkrrin| } t|_x6t| jD]"\} } |jd| d| qW||_||_||_||_||_ ||_ ||_ ||_ dS)Nrmrn) rrkrQitemsromethodr2rLrTrBparamsauthcookies) r7rtr2rLrTrBrurvrwrkrDrFr9r9r:__init__s         zRequest.__init__cCs d|jS)Nz)rt)r7r9r9r:__repr__szRequest.__repr__cCsht}|jd|jd|jd|jd|jd|jd|jd|jd|j d |j |S) zXConstructs a :class:`PreparedRequest ` for transmission and returns it.rtr2rLrTrBrurvrwrk) PreparedRequestpreparertr2rLrTrBrurvrwrk)r7r8r9r9r:r{s           zRequest.prepare)r`rarb__doc__rxryr{r9r9r9r:rrs  rrc @seZdZdZddZddddddddddd ZddZd d Zd d Zd dZ ddZ ddZ ddZ dddZ ddZddZdS)rzaThe 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', 'http://httpbin.org/get') >>> r = req.prepare() >>> s = requests.Session() >>> s.send(r) cCs=d|_d|_d|_d|_d|_t|_dS)N)rtr2rL_cookiesr^rrk)r7r9r9r:rxs      zPreparedRequest.__init__Nc Csh|j||j|||j||j||j|||j|||j| dS)z6Prepares the entire request with the given parameters.N)prepare_method prepare_urlprepare_headersprepare_cookies prepare_body prepare_auth prepare_hooks) r7rtr2rLrTrBrurvrwrkr9r9r:r{!s   zPreparedRequest.preparecCs d|jS)Nz)rt)r7r9r9r:ry1szPreparedRequest.__repr__cCsat}|j|_|j|_|jj|_|jj|_|j|_|j|_|S)N)rzrtr2rLcopyr}r^rk)r7r8r9r9r:r4s     zPreparedRequest.copycCs1||_|jdk r-|jj|_ndS)zPrepares the given HTTP method.N)rtupper)r7rtr9r9r:r~>s zPreparedRequest.prepare_methodc Csqyt|}Wn/tk r0t|}Yntk rAYnXd|krq|jjd rq||_dSt|\}}}}}}} |stdj |n|st d|ny|j dj d}Wnt k rt dYnX|pd } | r%| d 7} n| |7} |rL| dt|7} n|s[d }ntr t|tr|j d}nt| tr| j d} nt|tr|j d}nt|tr|j d}nt| tr | j d} q n|j|} | r@|r7d || f}q@| }ntt|| |d|| g}||_dS) zPrepares the given HTTP URL.:httpNzDInvalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?z Invalid URL %r: No host suppliedidnazutf-8zURL has an invalid label.r1@r/z%s&%s)unicode NameErrorr"UnicodeDecodeErrorlower startswithr2r rformatrrArO UnicodeErrorr%r?rGrr) r7r2ruschemervhostportr3r5fragmentnetloc enc_paramsr9r9r:rDsZ  " !       $zPreparedRequest.prepare_urlcCs;|r+tdd|jD|_n t|_dS)z Prepares the given HTTP headers.css'|]\}}t||fVqdS)N)r)rhrJvaluer9r9r:rjsz2PreparedRequest.prepare_headers..N)rrsrL)r7rLr9r9r:rs%zPreparedRequest.prepare_headersc Cs~d}d}d}tt|dt|ttttf g}yt|}Wn!tt t fk rvd}YnX|r|}|rt dn|dk rt ||j d` object, which contains a server's response to an HTTP request. _content status_coderLr2historyencodingreasonrwelapsedrequestcstt|jd|_d|_d|_t|_d|_d|_ d|_ g|_ d|_ t i|_tjd|_dS)NFr)superrrxr_content_consumedrrrLrawr2rrrrrwdatetime timedeltar)r7) __class__r9r:rxs         zResponse.__init__cs3jsjntfddjDS)Nc3s'|]}|t|dfVqdS)N)getattr)rhattr)r7r9r:rj6sz(Response.__getstate__..)rcontentr __attrs__)r7r9)r7r: __getstate__/s   zResponse.__getstate__cCsQx*|jD]\}}t|||q Wt|ddt|dddS)NrTr)rssetattr)r7staterJrr9r9r: __setstate__:szResponse.__setstate__cCs d|jS)Nz)r)r7r9r9r:ryBszResponse.__repr__cCs|jS)z,Returns true if :attr:`status_code` is 'OK'.)ok)r7r9r9r:__bool__EszResponse.__bool__cCs|jS)z,Returns true if :attr:`status_code` is 'OK'.)r)r7r9r9r: __nonzero__IszResponse.__nonzero__cCs |jdS)z,Allows you to use a response as an iterator.) iter_content)r7r9r9r:r=MszResponse.__iter__c Cs+y|jWntk r&dSYnXdS)NFT)raise_for_statusr)r7r9r9r:rQs   z Response.okcCsd|jko|jtkS)zTrue if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). location)rLrREDIRECT_STATI)r7r9r9r: is_redirectYszResponse.is_redirectcCstj|jdS)z6The apparent encoding, provided by the chardet libraryr)r&detectr)r7r9r9r:apparent_encoding`szResponse.apparent_encodingrFcsafdd}tj}|}jr?|n|}|r]t|}n|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. If decode_unicode is True, content will be decoded using the best available encoding based on the response. c3syy,x%jjddD] }|VqWWnatk rb}zt|WYdd}~Xn1tk r}zt|WYdd}~XnXWn:tk rx%jj}|sPn|VqWYnXd_dS)Ndecode_contentT) rstreamr*rr rrr<r)chunke) chunk_sizer7r9r:generateos # z'Response.iter_content..generate)rrrr)r7rdecode_unicoder reused_chunks stream_chunkschunksr9)rr7r:res  zResponse.iter_contentNccsd}x|jd|d|D]}|dk r>||}n|j}|r|dr|r|dd|dkr|j}nd}x|D] }|VqWqW|dk r|VndS) 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. Nrrrrrr)r splitlinespop)r7rrpendingrlinesliner9r9r: iter_liness   .   zResponse.iter_linesc Cs|jdkry^|jr*tdn|jdkrEd|_n'tj|jtpft|_Wqtk rd|_YqXnd|_|jS)z"Content of the response, in bytes.Fz2The content for this response was already consumedrNT) rr RuntimeErrorrr#r6rCONTENT_CHUNK_SIZEr)r7r9r9r:rs   +  zResponse.contentc Csd}|j}|js"tdS|jdkr=|j}nyt|j|dd}Wn-ttfk rt|jdd}YnX|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. Nr1errorsreplace)rrr"r LookupErrorr)r7rrr9r9r:texts    z Response.textc Ks|j rut|jdkrut|j}|dk ruy tj|jj||SWqrtk rnYqrXquntj|j|S)zReturns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. rIN) rrRrrr'loadsrOrr)r7kwargsrr9r9r:r's    z Response.jsoncCsj|jjd}i}|rft|}x9|D].}|jdpR|jd}|||d|j|jf}n8d|jkoXdknrvd|j|jf}n|rt|d|ndS) z2Raises stored :class:`HTTPError`, if one occurred.r1iiz%s Client Error: %siXz%s Server Error: %sresponseN)rrr)r7http_error_msgr9r9r:rszResponse.raise_for_statuscCs |jjS)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.* )r release_conn)r7r9r9r:closeszResponse.close)r`rarbr|rrxrrryrrr=rcrrrrITER_CHUNK_SIZErrrr'rrrr9r9)rr:rs:  (     *&  ri()Gr|rfriorrrkr structuresrrvrrwrr Zpackages.urllib3.fieldsr Zpackages.urllib3.filepostr Zpackages.urllib3.utilr Zpackages.urllib3.exceptionsr exceptionsrrrrrrutilsrrrrrrrrrrcompatrrr r!r"r#r$r%r&r'r(r)r* status_codesr+movedfoundothertemporary_movedrDEFAULT_REDIRECT_LIMITrrobjectr.rerrrzrr9r9r9r:s6  .FX mJ