3 g÷ÔYškã @sždZddlZddlZddlZddlmZddlmZddlm Z ddl m Z m Z m Z mZmZddlmZmZmZmZdd lmZmZmZdd lmZmZdd lmZdd lmZm Z dd l!m"Z"m#Z#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddlm*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ddl0m1Z1ddlm2Z2ej3ƒdk�rTy ej4Z5Wne6k �rPej7Z5YnXnejZ5e fdd„Z8e fdd„Z9Gdd„de:ƒZ;Gdd„de;ƒZJsz!merge_setting..)Ú isinstancerrÚupdateÚitems)Úrequest_settingÚsession_settingÚ dict_classÚmerged_settingZ none_keysÚkeyr&r&r*Ú merge_setting2s     r4cCs@|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)Úgetr4)Ú request_hooksÚ session_hooksr1r&r&r*Ú merge_hooksQs r9c@s6eZdZdd„Zddd„Zdd „Zd d „Zd d „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_targetbs    z(SessionRedirectMixin.get_redirect_targetFNTc ks.g} |j|ƒ} �x| �r(|jƒ} | j|ƒ| dd…|_y |jWn(tttfk rj|jj dd�YnXt |jƒ|j krŽt d|j |d�‚|j ƒ| jdƒr¼t|jƒ} dt| jƒ| f} t| ƒ}|jƒ} |jsät|jt| ƒƒ} nt| ƒ} t| ƒ| _|j| |ƒ|jtjtjfk�r>d}x|D]}| jj|dƒ�q Wd| _| j}y |d =Wntk �rdYnXt | 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.)r5z//z%s:%súContent-Lengthú Content-TypeúTransfer-EncodingÚCookie)ÚstreamÚtimeoutÚverifyÚcertÚproxiesÚallow_redirects)rErFrG)*rCÚcopyÚappendÚhistoryÚcontentrrÚ RuntimeErrorÚrawÚreadÚlenÚ max_redirectsrÚcloseÚ startswithr ÚurlrÚschemeÚgeturlÚnetlocr rÚrebuild_methodÚ status_coder#Útemporary_redirectÚpermanent_redirectr?ÚpopÚbodyÚKeyErrorr Ú_cookiesrÚcookiesÚprepare_cookiesÚrebuild_proxiesÚ rebuild_authÚ_body_positionr"Úsend)rArBÚreqrIrJrKrLrMÚyield_requestsÚadapter_kwargsÚhistrZÚprepared_requestÚ parsed_rurlÚparsedZpurged_headersÚheaderr?Z rewindabler&r&r*Úresolve_redirectswsr               z&SessionRedirectMixin.resolve_redirectscCsb|j}|j}d|kr:t|jjƒ}t|ƒ}|j|jkr:|d=|jrHt|ƒnd}|dk r^|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)r?rZr ÚrequestÚhostnameÚ trust_envrÚ prepare_auth)rArpr5r?rZÚoriginal_parsedÚredirect_parsedÚnew_authr&r&r*riãs   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) r?rZr r[rOr6r rxrÚ setdefaultr!rdr) rArprMr?rZr[Ú new_proxiesr}Z bypass_proxyÚenviron_proxiesÚproxyÚusernameÚpasswordr&r&r*rhûs*       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)Úmethodr_r#Ú see_otherÚfoundÚmoved)rArpr5rˆr&r&r*r^$sz#SessionRedirectMixin.rebuild_method)FNTNNF)Ú__name__Ú __module__Ú __qualname__rCrtrirhr^r&r&r&r*r:`s  k)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('http://httpbin.org/get') Or as a context manager:: >>> with requests.Session() as s: >>> s.get('http://httpbin.org/get') r?rfÚauthrMÚhooksÚparamsrKrLÚprefetchÚadaptersrIrxrWcCsrtƒ|_d|_i|_tƒ|_i|_d|_d|_d|_ t |_ d|_ t iƒ|_tƒ|_|jdtƒƒ|jdtƒƒdS)NFTzhttps://zhttp://)rr?r�rMrr‘r’rIrKrLrrWrxr rfrr”Úmountr)rAr&r&r*Ú__init__Ts zSession.__init__cCs|S)Nr&)rAr&r&r*Ú __enter__‹szSession.__enter__cGs |jƒdS)N)rX)rAÚ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 )r1) rˆrZÚfilesÚdataÚjsonr?r’r�rfr‘)rfr,rÚ CookieJarr rr r�rxrrZrÚpreparerˆÚupperršr›rœr4r?rr’r9r‘)rArvrfÚ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)añConstructs 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, 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ˆrZr?ršr›rœr’r�rfr‘)rJrN)rrŸr¢Úmerge_environment_settingsrZr-rk)rArˆrZr’r›r?rfršr�rJrNrMr‘rIrKrLrœrlÚprepÚsettingsÚ send_kwargsrBr&r&r*rv¹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 rNTr†)rrv)rArZÚkwargsr&r&r*r6s 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 rNTÚOPTIONS)rrv)rArZr§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 rNFr…)rrv)rArZr§r&r&r*Úheads 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, 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œ)rv)rArZr›rœr§r&r&r*Úpost!s z Session.postcKs|jd|fd|i|—ŽS)aYSends 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. :rtype: requests.Response ÚPUTr›)rv)rArZr›r§r&r&r*Úput-s z Session.putcKs|jd|fd|i|—ŽS)a[Sends 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. :rtype: requests.Response ÚPATCHr›)rv)rArZr›r§r&r&r*Úpatch8s 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)rv)rArZr§r&r&r*ÚdeleteCszSession.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 rIrKrLrMz#You can only send PreparedRequests.rNT)rZ)Úsecondsr5cSsg|]}|‘qSr&r&)r'rBr&r&r*r+€sz Session.send..rrm)rrIrKrLrMr,rÚ ValueErrorrbr6r‘Ú get_adapterrZÚpreferred_clockrkrÚelapsedrrQr rfrvrTrtÚinsertÚnextÚ_nextÚ StopIterationrR) rArvr§rNrIr‘ÚadapterÚstartÚrr¶rBÚgenrQr&r&r*rkMsB       "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)rKrMrIrL) rxr6rr.rÚosÚenvironr4rMrIrKrL) rArZrMrIrKrLr}Ú env_proxiesr(r)r&r&r*r£–s       z"Session.merge_environment_settingscCs:x(|jjƒD]\}}|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.ÚlowerrYr)rArZÚprefixr»r&r&r*r´³szSession.get_adaptercCs x|jjƒD] }|jƒq WdS)z+Closes all adapters and as such the sessionN)r”ÚvaluesrX)rAr)r&r&r*rXÁ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&)rV)r'r()rÅr&r*r+Ìsz!Session.mount..N)r”rb)rArÅr»Ú keys_to_mover3r&)rÅr*r•Æs  z Session.mountcst‡fdd„ˆjDƒƒ}|S)Nc3s|]}|tˆ|dƒfVqdS)N)Úgetattr)r'Úattr)rAr&r*ú Òsz'Session.__getstate__..)ÚdictÚ __attrs__)rAÚstater&)rAr*Ú __getstate__ÑszSession.__getstate__cCs&x |jƒD]\}}t|||ƒq WdS)N)r.Úsetattr)rArÍrÉÚvaluer&r&r*Ú __setstate__ÕszSession.__setstate__)NNNNNNNTNNNNNN)NN)N)N)rŒr�rŽÚ__doc__rÌr–r—r™r¢rvr6r©rªr«r­r¯r±rkr£r´rXr•rÎrÑr&r&r&r*r�;s2 7) D    I r�cCstƒS)zQ Returns a :class:`Session` for context-management. :rtype: Session )r�r&r&r&r*ÚsessionÚsrÓ)>rÒrÁÚplatformÚtimeÚ collectionsrÚdatetimerr�rÚcompatrrrr r rfr r r rÚmodelsrrrr‘rrÚ_internal_utilsrÚutilsrrÚ exceptionsrrrrÚ structuresrr”rrrrr r!r"Ú status_codesr#r$ÚsystemÚ perf_counterrµÚAttributeErrorÚclockr4r9Úobjectr:r�rÓr&r&r&r*Ú sB            \"