3

V'íc‹tã@s¤dZddlZddlZddlZddlmZddlmZddlm	Z	ddl
mZmZm
Z
mZmZddlmZmZmZmZdd	lmZmZmZdd
lmZmZddlmZddlmZm Z m!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/m0Z0m1Z1ddl2m3Z3ddlm4Z4ej5dkrZy
ej6Z7Wne8k
rVej9Z7YnXnejZ7efdd„Z:efdd„Z;Gdd„de<ƒZ=Gdd„de=ƒZ>dd„Z?dS)z•
requests.sessions
~~~~~~~~~~~~~~~~~

This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
éN)Ú	timedelta)ÚOrderedDicté)Ú_basic_auth_str)Ú	cookielibÚis_py3ÚurljoinÚurlparseÚMapping)Úcookiejar_from_dictÚextract_cookies_to_jarÚRequestsCookieJarÚ
merge_cookies)ÚRequestÚPreparedRequestÚDEFAULT_REDIRECT_LIMIT)Ú
default_hooksÚ
dispatch_hook)Úto_native_string)Úto_key_val_listÚdefault_headersÚ
DEFAULT_PORTS)ÚTooManyRedirectsÚ
InvalidSchemaÚChunkedEncodingErrorÚContentDecodingError)ÚCaseInsensitiveDict)ÚHTTPAdapter)Úrequote_uriÚget_environ_proxiesÚget_netrc_authÚshould_bypass_proxiesÚget_auth_from_urlÚrewind_bodyÚresolve_proxies)Úcodes)ÚREDIRECT_STATIÚwin32cCst|dkr|S|dkr|St|tƒo*t|tƒs0|S|t|ƒƒ}|jt|ƒƒdd„|jƒDƒ}x|D]
}||=qbW|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`
    NcSsg|]\}}|dkr|‘qS)N©)Ú.0ÚkÚvr(r(ú5/tmp/pip-build-gk9425m9/requests/requests/sessions.pyú
<listcomp>Jsz!merge_setting.<locals>.<listcomp>)Ú
isinstancer
rÚupdateÚitems)Úrequest_settingÚsession_settingÚ
dict_classÚmerged_settingÚ	none_keysÚkeyr(r(r,Ú
merge_setting2s



r7cCs@|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)Úgetr7)Ú
request_hooksÚ
session_hooksr3r(r(r,Úmerge_hooksQs
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_targetbs


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)rHN)rJN)r	ÚhostnameÚschemeÚportrr9)rDÚold_urlÚnew_urlÚ
old_parsedÚ
new_parsedZchanged_portZchanged_schemeÚdefault_portr(r(r,Úshould_strip_authws
z&SessionRedirectMixin.should_strip_authFNTc	ksRg}
|j|ƒ}t|jƒj}x0|rL|jƒ}
|
j|ƒ|
dd…|_y
|jWn(tt	t
fk
rv|jjddYnXt
|jƒ|jkrœtdj|jƒ|d‚|jƒ|jdƒrÌt|jƒ}djt|jƒ|gƒ}t|ƒ}|jd	krð|rð|j|d
}n|jrü|j}|jƒ}|jst|jt|ƒƒ}nt|ƒ}t|ƒ|
_|j|
|ƒ|jtjtjfkrxd}x|D]}|
j j!|dƒqZWd|
_"|
j }|j!ddƒt#|
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 {} redirects.)r8z//ú:Ú)ÚfragmentúContent-LengthúContent-TypeúTransfer-EncodingÚCookie)ÚstreamÚtimeoutÚverifyÚcertÚproxiesÚallow_redirects)rXrYrZ)-rFr	ÚurlrWÚcopyÚappendÚhistoryÚcontentrrÚRuntimeErrorÚrawÚreadÚlenÚ
max_redirectsrÚformatÚcloseÚ
startswithÚjoinrrLÚ_replaceÚgeturlÚnetlocrrÚrebuild_methodÚstatus_coder%Útemporary_redirectÚpermanent_redirectrBÚpopÚbodyrÚ_cookiesrÚcookiesÚprepare_cookiesÚrebuild_proxiesÚrebuild_authÚ_body_positionr#Úsend)rDrEÚreqr\r]r^r_r`Úyield_requestsÚadapter_kwargsÚhistrbZprevious_fragmentÚprepared_requestÚparsed_rurlÚparsedÚpurged_headersÚheaderrBÚ
rewindabler(r(r,Úresolve_redirectssv








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)rBrbrSÚrequestÚ	trust_envr Úprepare_auth)rDr„r8rBrbÚnew_authr(r(r,r}þsz!SessionRedirectMixin.rebuild_authcCsz|j}t|jƒj}t|||jƒ}d|kr.|d=yt||ƒ\}}Wntk
r^d\}}YnX|rv|rvt||ƒ|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
        zProxy-AuthorizationN)NN)	rBr	rbrLr$rr"ÚKeyErrorr)rDr„r`rBrLÚnew_proxiesÚusernameÚpasswordr(r(r,r|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)Úmethodrtr%Ú	see_otherÚfoundÚmoved)rDr„r8r—r(r(r,rs-sz#SessionRedirectMixin.rebuild_method)FNTNNF)	Ú__name__Ú
__module__Ú__qualname__rFrSrŠr}r|rsr(r(r(r,r=`s
mr=c@sÌeZdZdZdddddddd	d
ddd
gZdd„Zdd„Zdd„Zdd„Zd6dd„Z	dd„Z
dd„Zdd„Zd7d d!„Z
d8d"d#„Zd9d$d%„Zd&d'„Zd(d)„Zd*d+„Zd,d-„Zd.d/„Zd0d1„Zd2d3„Zd4d5„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')
      <Response [200]>

    Or as a context manager::

      >>> with requests.Session() as s:
      ...     s.get('https://httpbin.org/get')
      <Response [200]>
    rBrzÚauthr`ÚhooksÚparamsr^r_Úadaptersr\rrkcCsrtƒ|_d|_i|_tƒ|_i|_d|_d|_d|_	t
|_d|_t
iƒ|_tƒ|_|jdtƒƒ|jdtƒƒdS)NFTzhttps://zhttp://)rrBrŸr`rr r¡r\r^r_rrkrrrzrr¢Úmountr)rDr(r(r,Ú__init__]s

zSession.__init__cCs|S)Nr()rDr(r(r,Ú	__enter__›szSession.__enter__cGs|jƒdS)N)rm)rDÚ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 <PreparedRequest>` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request <Request>` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        :rtype: requests.PreparedRequest
        )r3)
r—rbÚfilesÚdataÚjsonrBr¡rŸrzr )rzr.rÚ	CookieJarrrr
rŸrr rbrÚpreparer—Úupperr¨r©rªr7rBrr¡r<r )rDrŒrzÚ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)ax	Constructs a :class:`Request <Request>`, prepares it and sends it.
        Returns :class:`Response <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) <timeouts>` 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``. When set to
            ``False``, requests will accept any TLS certificate presented by
            the server, and will ignore hostname mismatches and/or expired
            certificates, which will make your application vulnerable to
            man-in-the-middle (MitM) attacks. Setting verify to ``False`` 
            may be useful during local development or testing.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        )
r—rbrBr¨r©rªr¡rŸrzr )r]ra)rr­r°Úmerge_environment_settingsrbr/r)rDr—rbr¡r©rBrzr¨rŸr]rar`r r\r^r_rªr€ÚprepÚsettingsÚsend_kwargsrEr(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
        raTr•)Ú
setdefaultrŒ)rDrbÚkwargsr(r(r,r9szSession.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
        raTÚOPTIONS)rµrŒ)rDrbr¶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
        raFr”)rµrŒ)rDrbr¶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Œ)rDrbr©rªr¶r(r(r,Úpost6sz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Œ)rDrbr©r¶r(r(r,ÚputCs
zSession.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Œ)rDrbr©r¶r(r(r,ÚpatchOs
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Œ)rDrbr¶r(r(r,Údelete[szSession.deletec
KsŽ|jd|jƒ|jd|jƒ|jd|jƒd|krFt||j|jƒ|d<t|tƒrXt	dƒ‚|j
ddƒ}|jdƒ}|j}|j
|jd}tƒ}|j|f|Ž}tƒ|}	t|	d	|_td
||f|Ž}|jräx |jD]}
t|j|
j|
jƒqÊWt|j||jƒ|r|j||f|Ž}dd„|Dƒ}ng}|r>|jd
|ƒ|j
ƒ}||_|s~y"t|j||fddi|—Žƒ|_Wntk
r|YnX|sŠ|j|S)zISend a given PreparedRequest.

        :rtype: requests.Response
        r\r^r_r`z#You can only send PreparedRequests.raT)rb)Úsecondsr8cSsg|]}|‘qSr(r()r)rEr(r(r,r-›sz Session.send.<locals>.<listcomp>rr)rµr\r^r_r$r`rr.rÚ
ValueErrorrwr9r Úget_adapterrbÚpreferred_clockrrÚelapsedrrerrzrŒrhrŠÚinsertÚnextÚ_nextÚ
StopIterationrf)
rDrŒr¶rar\r ÚadapterÚstartÚrrÅrEÚgenrer(r(r,resJ


"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
        NÚno_proxy)rÎTÚREQUESTS_CA_BUNDLEÚCURL_CA_BUNDLE)r^r`r\r_)rr9rr0rµÚosÚenvironr7r`r\r^r_)
rDrbr`r\r^r_rÎÚenv_proxiesr*r+r(r(r,r±³sz"Session.merge_environment_settingscCs@x,|jjƒD]\}}|jƒj|jƒƒr|SqWtdj|ƒƒ‚dS)z~
        Returns the appropriate connection adapter for the given URL.

        :rtype: requests.adapters.BaseAdapter
        z*No connection adapters were found for {!r}N)r¢r0Úlowerrnrrl)rDrbÚprefixrÊr(r(r,rÃÐszSession.get_adaptercCs x|jjƒD]}|jƒqWdS)z+Closes all adapters and as such the sessionN)r¢Úvaluesrm)rDr+r(r(r,rmÞ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()rj)r)r*)rÕr(r,r-ész!Session.mount.<locals>.<listcomp>N)r¢rw)rDrÕrÊÚkeys_to_mover6r()rÕr,r£ãs

z
Session.mountcs‡fdd„ˆjDƒ}|S)Ncsi|]}tˆ|dƒ|“qS)N)Úgetattr)r)Úattr)rDr(r,ú
<dictcomp>ïsz(Session.__getstate__.<locals>.<dictcomp>)Ú	__attrs__)rDÚstater()rDr,Ú__getstate__îszSession.__getstate__cCs&x |jƒD]\}}t|||ƒq
WdS)N)r0Úsetattr)rDrÜrÙÚvaluer(r(r,Ú__setstate__òszSession.__setstate__)NNNNNNNTNNNNNN)NN)N)N)r›rœrÚ__doc__rÛr¤r¥r§r°rŒr9r¸r¹rºr¼r¾rÀrr±rÃrmr£rÝràr(r(r(r,ržDs2>)
I



Nrž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ÚdatetimerÚcollectionsrrŸrÚcompatrrrr	r
rzrrr
rÚmodelsrrrr rrÚ_internal_utilsrÚutilsrrrÚ
exceptionsrrrrÚ
structuresrr¢rrrr r!r"r#r$Ústatus_codesr%r&ÚplatformÚperf_counterrÄÚAttributeErrorÚclockr7r<Úobjectr=ržrâr(r(r(r,Ú<module>	sB$
e6