3 ¦˜‚]”rã @s˜dZddlZddlZddlZddlmZddlmZddlm Z m Z m Z m Z m Z mZddlmZmZmZmZddlmZmZmZdd lmZmZdd lmZdd lmZmZm Z dd l!m"Z"m#Z#m$Z$m%Z%dd l&m'Z'ddl(m)Z)ddlm*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ddl0m1Z1ddlm2Z2ej3dk�rNy ej4Z5Wne6k �rJej7Z5YnXnejZ5e fdd„Z8e fdd„Z9Gdd„de:ƒZ;Gdd„de;ƒZIsz!merge_setting..)Ú isinstancer rÚupdateÚitems)Úrequest_settingÚsession_settingÚ dict_classÚmerged_settingÚ none_keysÚkeyr'r'r+Ú merge_setting1s     r6cCs@|dks|jdƒgkr|S|dks0|jdƒgkr4|St|||ƒS)z©Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. NÚresponse)Úgetr6)Ú request_hooksÚ session_hooksr2r'r'r+Ú merge_hooksPs r;c@s>eZdZdd„Zdd„Zddd „Zd d „Zd d „Zdd„ZdS)ÚSessionRedirectMixincCs,|jr(|jd}tr|jdƒ}t|dƒSdS)z7Receives a Response. Returns a redirect URI or ``None``ÚlocationÚlatin1Úutf8N)Ú is_redirectÚheadersrÚencoder)ÚselfÚrespr=r'r'r+Úget_redirect_targetas    z(SessionRedirectMixin.get_redirect_targetcCsœt|ƒ}t|ƒ}|j|jkr dS|jdkrL|jdkrL|jdkrL|jd krLdS|j|jk}|j|jk}tj|jdƒdf}| r”|j|kr”|j|kr”dS|pš|S) zFDecide whether Authorization header should be removed when redirectingTÚhttpéPNÚhttpsé»F)rGN)rIN)r ÚhostnameÚschemeÚportrr8)rCÚold_urlÚnew_urlÚ old_parsedÚ new_parsedZ changed_portZchanged_schemeÚ default_portr'r'r+Úshould_strip_authvs    z&SessionRedirectMixin.should_strip_authFNTc ksdg} |j|ƒ} t|jƒj} �xB| �r^|jƒ} | j|ƒ| dd…|_y |jWn(tt t fk rv|j j dd�YnXt |jƒ|jkrštd|j|d�‚|jƒ| jdƒrÈt|jƒ}dt|jƒ| f} t| ƒ}|jd krì| rì|j| d �}n |jrø|j} |jƒ} |j�st|jt| ƒƒ} nt| ƒ} t| ƒ| _|j| |ƒ|jtjtjfk�rtd}x|D]}| jj|dƒ�qVWd| _ | j}y |d=Wnt!k �ršYnXt"| j#||j ƒt$| j#|j%ƒ| j&| j#ƒ|j'| |ƒ}|j(| |ƒ| j)dk �oúd |k�púd |k}|�r t*| ƒ| }|�r|Vq|j+|f|||||ddœ| —Ž}t"|j%| |j ƒ|j|ƒ} |VqWdS)zBReceives a Response. Returns a generator of Responses or Requests.rNF)Údecode_contentzExceeded %s redirects.)r7z//z%s:%sÚ)ÚfragmentúContent-Lengthú Content-TypeúTransfer-EncodingÚCookie)ÚstreamÚtimeoutÚverifyÚcertÚproxiesÚallow_redirects)rVrWrX),rEr ÚurlrUÚcopyÚappendÚhistoryÚcontentrrÚ RuntimeErrorÚrawÚreadÚlenÚ max_redirectsrÚcloseÚ startswithrrKÚ_replaceÚgeturlÚnetlocrrÚrebuild_methodÚ status_coder$Útemporary_redirectÚpermanent_redirectrAÚpopÚbodyÚKeyErrorr Ú_cookiesrÚcookiesÚprepare_cookiesÚrebuild_proxiesÚ rebuild_authÚ_body_positionr#Úsend)rCrDÚreqrZr[r\r]r^Úyield_requestsÚadapter_kwargsÚhistr`Zprevious_fragmentÚprepared_requestÚ parsed_rurlÚparsedÚpurged_headersÚheaderrAÚ rewindabler'r'r+Úresolve_redirects�s|                z&SessionRedirectMixin.resolve_redirectscCsR|j}|j}d|kr*|j|jj|ƒr*|d=|jr8t|ƒnd}|dk rN|j|ƒdS)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)rAr`rRÚrequestÚ trust_envr Ú prepare_auth)rCr�r7rAr`Únew_authr'r'r+rzs z!SessionRedirectMixin.rebuild_authc CsØ|dk r |ni}|j}|j}t|ƒj}|jƒ}|jdƒ}t||d�}|jr~| r~t||d�} | j|| jdƒƒ} | r~|j || ƒd|krŒ|d=yt ||ƒ\} } Wnt k r¼d\} } YnX| rÔ| rÔt | | ƒ|d<|S)a°This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict NÚno_proxy)r�ÚallzProxy-Authorization)NN) rAr`r rKrar8r!rŠrÚ setdefaultr"rur) rCr�r^rAr`rKÚ new_proxiesr�Ú bypass_proxyÚenviron_proxiesÚproxyÚusernameÚpasswordr'r'r+rys*       z$SessionRedirectMixin.rebuild_proxiescCsX|j}|jtjkr|dkrd}|jtjkr6|dkr6d}|jtjkrN|dkrNd}||_dS)z‚When being redirected we may want to change the method of the request based on certain specs or browser behavior. ÚHEADÚGETÚPOSTN)Úmethodrpr$Ú see_otherÚfoundÚmoved)rCr�r7r™r'r'r+ro=sz#SessionRedirectMixin.rebuild_method)FNTNNF) Ú__name__Ú __module__Ú __qualname__rErRr‡rzryror'r'r'r+r<_s p)r<c@sÎeZdZdZdddddddd d d d d dg Zdd„Zdd„Zdd„Zdd„Zd7dd„Z dd„Z dd„Z dd „Z d8d!d"„Z d9d#d$„Zd:d%d&„Zd'd(„Zd)d*„Zd+d,„Zd-d.„Zd/d0„Zd1d2„Zd3d4„Zd5d6„ZdS);ÚSessiona€A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage:: >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') Or as a context manager:: >>> with requests.Session() as s: >>> s.get('https://httpbin.org/get') rArwÚauthr^ÚhooksÚparamsr\r]ÚprefetchÚadaptersrZrŠricCsrtƒ|_d|_i|_tƒ|_i|_d|_d|_d|_ t |_ d|_ t iƒ|_tƒ|_|jdtƒƒ|jdtƒƒdS)NFTzhttps://zhttp://)rrAr¡r^rr¢r£rZr\r]rrirŠr rwrr¥Úmountr)rCr'r'r+Ú__init__ms zSession.__init__cCs|S)Nr')rCr'r'r+Ú __enter__¤szSession.__enter__cGs |jƒdS)N)rj)rCÚargsr'r'r+Ú__exit__§szSession.__exit__c Cs¶|jpi}t|tjƒst|ƒ}tttƒ|jƒ|ƒ}|j}|jrV| rV|j rVt |j ƒ}t ƒ}|j |j jƒ|j |j|j|jt|j|jtd�t|j|jƒt||jƒ|t|j|jƒd� |S)a‹Constructs 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. :rtype: requests.PreparedRequest )r2) r™r`ÚfilesÚdataÚjsonrAr£r¡rwr¢)rwr-rÚ CookieJarr rr r¡rŠr r`rÚpreparer™Úupperr«r¬r­r6rArr£r;r¢)rCr‰rwÚmerged_cookiesr¡Úpr'r'r+Úprepare_requestªs*     zSession.prepare_requestNTc Cstt|jƒ||||pi||pi||| d� }|j|ƒ}| p8i} |j|j| | ||ƒ}| | dœ}|j|ƒ|j|f|Ž}|S)aConstructs 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, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json 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) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) ` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response ) r™r`rAr«r¬r­r£r¡rwr¢)r[r_)rr°r³Úmerge_environment_settingsr`r.r|)rCr™r`r£r¬rArwr«r¡r[r_r^r¢rZr\r]r­r}ÚprepÚsettingsÚ send_kwargsrDr'r'r+r‰Òs()  zSession.requestcKs|jddƒ|jd|f|ŽS)zåSends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response r_Tr—)r�r‰)rCr`Úkwargsr'r'r+r8s z Session.getcKs|jddƒ|jd|f|ŽS)zéSends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response r_TÚOPTIONS)r�r‰)rCr`r¸r'r'r+Úoptions$s zSession.optionscKs|jddƒ|jd|f|ŽS)zæSends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response r_Fr–)r�r‰)rCr`r¸r'r'r+Úhead/s z Session.headcKs|jd|f||dœ|—ŽS)aÈSends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response r˜)r¬r­)r‰)rCr`r¬r­r¸r'r'r+Úpost:s z Session.postcKs|jd|fd|i|—ŽS)auSends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response ÚPUTr¬)r‰)rCr`r¬r¸r'r'r+ÚputGs z Session.putcKs|jd|fd|i|—ŽS)awSends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response ÚPATCHr¬)r‰)rCr`r¬r¸r'r'r+ÚpatchSs z Session.patchcKs|jd|f|ŽS)zèSends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response ÚDELETE)r‰)rCr`r¸r'r'r+Údelete_szSession.deletec Ks~|jd|jƒ|jd|jƒ|jd|jƒ|jd|jƒt|tƒrJtdƒ‚|jddƒ}|j dƒ}|j }|j |j d�}t ƒ}|j|f|Ž}t ƒ|} t| d �|_td ||f|Ž}|jrÖx |jD]} t|j| j| jƒq¼Wt|j||jƒ|j||f|Ž} |�r d d „| Dƒng} | �r.| jd |ƒ| jƒ}| |_|�sny"t|j||fddi|—Žƒ|_Wntk �rlYnX|�sz|j|S)zISend a given PreparedRequest. :rtype: requests.Response rZr\r]r^z#You can only send PreparedRequests.r_T)r`)Úsecondsr7cSsg|]}|‘qSr'r')r(rDr'r'r+r,œsz Session.send..rr~)r�rZr\r]r^r-rÚ ValueErrorrsr8r¢Ú get_adapterr`Úpreferred_clockr|rÚelapsedrrcr rwr‰rfr‡ÚinsertÚnextÚ_nextÚ StopIterationrd) rCr‰r¸r_rZr¢ÚadapterÚstartÚrrÇrDÚgenrcr'r'r+r|isB       "z Session.sendc Cs°|jrr|dk r|jdƒnd}t||d�}x |jƒD]\}} |j|| ƒq2W|dksZ|dkrrtjjdƒpptjjdƒ}t||jƒ}t||j ƒ}t||j ƒ}t||j ƒ}||||dœS)z^ Check the environment and merge it with some settings. :rtype: dict Nr�)r�TÚREQUESTS_CA_BUNDLEÚCURL_CA_BUNDLE)r\r^rZr]) rŠr8rr/r�ÚosÚenvironr6r^rZr\r]) rCr`r^rZr\r]r�Ú env_proxiesr)r*r'r'r+r´²s       z"Session.merge_environment_settingscCs>x,|jjƒD]\}}|jƒj|jƒƒr |Sq Wtd|ƒ‚dS)z~ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter z*No connection adapters were found for '%s'N)r¥r/Úlowerrkr)rCr`ÚprefixrÌr'r'r+rÅÏszSession.get_adaptercCs x|jjƒD] }|jƒq WdS)z+Closes all adapters and as such the sessionN)r¥Úvaluesrj)rCr*r'r'r+rjÝsz Session.closecsB||jˆ<‡fdd„|jDƒ}x|D]}|jj|ƒ|j|<q$WdS)zwRegisters a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. cs g|]}t|ƒtˆƒkr|‘qSr')rh)r(r))rÖr'r+r,èsz!Session.mount..N)r¥rs)rCrÖrÌÚ keys_to_mover5r')rÖr+r¦âs  z Session.mountcs‡fdd„ˆjDƒ}|S)Ncsi|]}tˆ|dƒ|“qS)N)Úgetattr)r(Úattr)rCr'r+ú îsz(Session.__getstate__..)Ú __attrs__)rCÚstater')rCr+Ú __getstate__íszSession.__getstate__cCs&x |jƒD]\}}t|||ƒq WdS)N)r/Úsetattr)rCrÝrÚÚvaluer'r'r+Ú __setstate__ñszSession.__setstate__)NNNNNNNTNNNNNN)NN)N)N)r�ržrŸÚ__doc__rÜr§r¨rªr³r‰r8rºr»r¼r¾rÀrÂr|r´rÅrjr¦rÞrár'r'r'r+r Ts2 7) D    I r cCstƒS)aZ Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session )r r'r'r'r+Úsessionös rã)>rârÒÚsysÚtimeÚdatetimerr¡rÚcompatrrrrr r rwr r r rÚmodelsrrrr¢rrÚ_internal_utilsrÚutilsrrrÚ exceptionsrrrrÚ structuresrr¥rrrr r!r"r#Ú status_codesr$r%ÚplatformÚ perf_counterrÆÚAttributeErrorÚclockr6r;Úobjectr<r rãr'r'r'r+Ú s@             v%