ReW@sdZddlZddlmZddlmZddlmZddlmZm Z m Z m Z m Z ddl mZmZmZmZdd lmZmZmZdd lmZmZdd lmZmZmZdd lmZmZm Z m!Z!dd l"m#Z#ddl$m%Z%ddlm&Z&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,ddlm-Z-e ddZ.e ddZ/Gddde0Z1Gddde1Z2ddZ3dS)z requests.session ~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). N)Mapping)datetime)_basic_auth_str) cookielib OrderedDicturljoinurlparse builtin_str)cookiejar_from_dictextract_cookies_to_jarRequestsCookieJar merge_cookies)RequestPreparedRequestDEFAULT_REDIRECT_LIMIT) default_hooks dispatch_hook)to_key_val_listdefault_headersto_native_string)TooManyRedirects InvalidSchemaChunkedEncodingErrorContentDecodingError)CaseInsensitiveDict) HTTPAdapter) requote_uriget_environ_proxiesget_netrc_authshould_bypass_proxiesget_auth_from_url)codes)REDIRECT_STATIcCs|dkr|S|dkr |St|to;t|tsB|S|t|}|jt|x0|jD]"\}}|dkrt||=qtqtWtdd|jD}|S)z Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` Ncss-|]#\}}|dk r||fVqdS)N).0kvr$r$8/tmp/pip-ztkk0jow-build/pip/_vendor/requests/sessions.py Csz merge_setting..) isinstancerrupdateitemsdict)request_settingsession_setting dict_classmerged_settingr&r'r$r$r( merge_setting's   r2cCsZ|dks!|jdgkr%|S|dksF|jdgkrJ|St|||S)z Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. Nresponse)getr2) request_hooks session_hooksr0r$r$r( merge_hooksHs !!r7c@sCeZdZdddddddZddZdd ZdS) SessionRedirectMixinFNTccsd}x|jr|j} y |jWn.tttfk rY|jjddYnX||jkrt d|jn|j |j d} |j } | j drt|j} d| j| f} nt| } | j} t| jst|jt| } n t| } t| | _|jtjkrW| dkrWd } n|jtjkr~| dkr~d } n|jtjkr| d krd } n| | _ |jtjtjfkrd | j kr| j d =nd | _n| j }y |d =Wntk rYnXt| j | |j| j j!|j"| j#| j |j$| |}|j%| || }|j&|d|d|d|d|d|dd}t|j"| |j|d7}|Vq Wd S)z6Receives a Response. Returns a generator of Responses.rdecode_contentFzExceeded %s redirects.locationz//z%s:%sHEADGETPOSTzContent-LengthNCookiestreamtimeoutverifycertproxiesallow_redirectsr)' is_redirectcopycontentrr RuntimeErrorrawread max_redirectsrcloseheadersmethod startswithr urlschemegeturlnetlocrrr status_coder" see_otherfoundmoved temporaryresumebodyKeyErrorr _cookiesr+cookiesprepare_cookiesrebuild_proxies rebuild_authsend)selfrespreqr?r@rArBrCiprepared_requestrPrN parsed_rurlparsedrMr$r$r(resolve_redirectsYsn                     z&SessionRedirectMixin.resolve_redirectscCs|j}|j}d|kr[t|jj}t|}|j|jkr[|d=q[n|jrpt|nd}|dk r|j|ndS)z When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. AuthorizationN)rMrPr requesthostname trust_envr prepare_auth)rbrfr3rMrPoriginal_parsedredirect_parsednew_authr$r$r(r`s      z!SessionRedirectMixin.rebuild_authc Cs|j}|j}t|j}|dk r9|jni}|jrt| rt|}|j|}|r|j |||qnd|kr|d=nyt ||\} } Wnt k rd\} } YnX| r| rt | | |d>> import requests >>> s = requests.Session() >>> s.get('http://httpbin.org/get') 200 rMr]authr@rChooksparamsrArBprefetchadaptersr?rmrKcCst|_d|_i|_t|_i|_d|_d|_d|_ t |_ d|_ t i|_t|_|jdt|jdtdS)NFTzhttps://zhttp://)rrMr|rCrr}r~r?rArBrrKrmr r]rrmountr)rbr$r$r(__init__ s           zSession.__init__cCs|S)Nr$)rbr$r$r( __enter__?szSession.__enter__cGs|jdS)N)rL)rbargsr$r$r(__exit__BszSession.__exit__cCs!|jp i}t|tjs0t|}nttt|j|}|j}|jr| r|j rt |j }nt }|j d|j jd|j d|jd|jdt|j|jdtdt|j|jdt||jd |d t|j|j |S) abConstructs a :class:`PreparedRequest ` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request ` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. rNrPfilesdatarMr0r~r|r]r})r]r*r CookieJarr rr r|rmrrPrpreparerNupperrrr2rMrr~r7r})rbrkr]merged_cookiesr|pr$r$r(prepare_requestEs(       zSession.prepare_requestNTcCst|}td|jd|d|d|d|p9id|pEid|d|d | }|j|}| pui} |jrt|pi}x*|jD]\}}| j||qW| r|d k rtj j d }n| r|d k rtj j d }qnt | |j } t | |j } t ||j}t ||j}i| d 6| d6|d6|d6| d6| d6}|j||}|S)a4Constructs a :class:`Request `, prepares it and sends it. Returns :class:`Response ` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) Float describing the timeout of the request in seconds. :param allow_redirects: (optional) Boolean. Set to True by default. :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. rNrPrMrrr~r|r]r}FREQUESTS_CA_BUNDLECURL_CA_BUNDLEr?r@rArBrCrD)r rrrrmrr,rrosenvironr4r2rCr?rArBra)rbrNrPr~rrMr]rr|r@rDrCr}r?rArBrdprep env_proxiesr&r' send_kwargsrcr$r$r(rklsD,        zSession.requestcKs#|jdd|jd||S)zSends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. rDTr<)rrrk)rbrPkwargsr$r$r(r4sz Session.getcKs#|jdd|jd||S)zSends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. rDTOPTIONS)rrrk)rbrPrr$r$r(optionsszSession.optionscKs#|jdd|jd||S)zSends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. rDFr;)rrrk)rbrPrr$r$r(headsz Session.headcKs|jd|d||S)a8Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. r=r)rk)rbrPrrr$r$r(postsz Session.postcKs|jd|d||S)a7Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. PUTr)rk)rbrPrrr$r$r(putsz Session.putcKs|jd|d||S)a9Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. PATCHr)rk)rbrPrrr$r$r(patchsz Session.patchcKs|jd||S)zSends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. DELETE)rk)rbrPrr$r$r(deleteszSession.deletec Ks |jd|j|jd|j|jd|j|jd|jt|tsjtdn|jdd}|j d}|j d}|j d}|j d}|j d}|j } |j d |j } t j} | j||} t j| | _td | | |} | jrdx-| jD]} t|j| j| jq>Wnt|j|| j|j| |d|d|d|d|d|}|rd d |Dng}|r|jd | |j} || _n|s| jn| S)zSend a given PreparedRequest.r?rArBrCz#You can only send PreparedRequests.rDTr@rPr3cSsg|] }|qSr$r$)r%rcr$r$r( Is z Session.send..r)rrr?rArBrCr*r ValueErrorpopr4r} get_adapterrPrutcnowraelapsedrhistoryr r]rkrIriinsertrG)rbrkrrDr?r@rArBrCr}adapterstartrrcgenrr$r$r(rasH        z Session.sendcCsMx6|jjD]%\}}|jj|r|SqWtd|dS)z>Returns the appropriate connnection adapter for the given URL.z*No connection adapters were found for '%s'N)rr,lowerrOr)rbrPprefixrr$r$r(rXszSession.get_adaptercCs(x!|jjD]}|jqWdS)z+Closes all adapters and as such the sessionN)rvaluesrL)rbr'r$r$r(rLbsz Session.closecsW||j<fdd|jD}x'|D]}|jj||j|.N)rr)rbrr keys_to_movekeyr$)rr(rgs  z Session.mountcs tfddjDS)Nc3s'|]}|t|dfVqdS)N)getattr)r%attr)rbr$r(r)ssz'Session.__getstate__..)r- __attrs__)rbr$)rbr( __getstate__rszSession.__getstate__cCs1x*|jD]\}}t|||q WdS)N)r,setattr)rbstatervaluer$r$r( __setstate__uszSession.__setstate__)rxryrz__doc__rrrrrrkr4rrrrrrrarrLrrrr$r$r$r(r{sD   3   (S    G  r{cCstS)z2Returns a :class:`Session` for context-management.)r{r$r$r$r(sessionzsr)4rr collectionsrrr|rcompatrrrr r r]r r r rmodelsrrrr}rrutilsrrr exceptionsrrrr structuresrrrrrrr r! status_codesr"r#r2r7objectr8r{rr$r$r$r( s* (""(!