ó  fH^c@sdZddlZddlZddlZddlmZddlmZddlm 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/ddl0m1Z1ddlm2Z2ej3dkrÄy ej4Z5Wne6k rÀej7Z5nXn ejZ5e d„Z8e d„Z9de:fd„ƒYZ;de;fd„ƒYZ<d„Z=dS(s“ requests.session ~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). iÿÿÿÿN(t timedeltai(t_basic_auth_str(t cookielibtis_py3t OrderedDictturljointurlparsetMapping(tcookiejar_from_dicttextract_cookies_to_jartRequestsCookieJart merge_cookies(tRequesttPreparedRequesttDEFAULT_REDIRECT_LIMIT(t default_hookst dispatch_hook(tto_native_string(tto_key_val_listtdefault_headerst DEFAULT_PORTS(tTooManyRedirectst InvalidSchematChunkedEncodingErrortContentDecodingError(tCaseInsensitiveDict(t HTTPAdapter(t requote_uritget_environ_proxiestget_netrc_authtshould_bypass_proxiestget_auth_from_urlt rewind_body(tcodes(tREDIRECT_STATItwin32cCs´|dkr|S|dkr |St|tƒo;t|tƒsB|S|t|ƒƒ}|jt|ƒƒg|jƒD]\}}|dkrt|^qt}x|D] }||=qŸW|S(sè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` N(tNonet isinstanceRRtupdatetitems(trequest_settingtsession_settingt dict_classtmerged_settingtktvt none_keystkey((srequests/sessions.pyt merge_setting1s  1  cCsZ|dks!|jdƒgkr%|S|dksF|jdƒgkrJ|St|||ƒS(s©Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. tresponseN(R$tgetR0(t request_hookst session_hooksR*((srequests/sessions.pyt merge_hooksPs !!tSessionRedirectMixincBsPeZd„Zd„Zededded„Zd„Zd„Z d„Z RS(cCs?|jr;|jd}tr.|jdƒ}nt|dƒSdS(s7Receives a Response. Returns a redirect URI or ``None``tlocationtlatin1tutf8N(t is_redirecttheadersRtencodeRR$(tselftrespR7((srequests/sessions.pytget_redirect_targetas    cCsàt|ƒ}t|ƒ}|j|jkr.tS|jdkrn|jdkrn|jdkrn|jdkrntS|j|jk}|j|jk}tj|jdƒdf}| rÖ|j|krÖ|j|krÖtS|pß|S(sFDecide whether Authorization header should be removed when redirectingthttpiPthttpsi»N(iPN(i»N( RthostnametTruetschemetportR$tFalseRR2(R=told_urltnew_urlt old_parsedt new_parsedt changed_porttchanged_schemet default_port((srequests/sessions.pytshould_strip_authvs  c ks9g} |j|ƒ} t|jƒj} x | r4|jƒ} | j|ƒ| d|_y |jWn-tt t fk r�|j j dt ƒnXt|jƒ|jkrÅtd|jd|ƒ‚n|jƒ| jdƒr t|jƒ}dt|jƒ| f} nt| ƒ}|jdkr?| r?|jd| ƒ}n|jrT|j} n|jƒ} |js„t|jt| ƒƒ} n t| ƒ} t| ƒ| _|j| |ƒ|jtjtjfkrd}x!|D]}| jj |dƒq×Wd| _"n| j}y |d =Wnt#k r'nXt$| j%||j ƒt&| j%|j'ƒ| j(| j%ƒ|j)| |ƒ}|j*| |ƒ| j+dk o§d |kp§d |k}|r½t,| ƒn| }|rÑ|Vq*|j-|d |d|d|d|d|dt | �}t$|j'| |j ƒ|j|ƒ} |Vq*WdS(sBReceives a Response. Returns a generator of Responses or Requests.itdecode_contentsExceeded %s redirects.R1s//s%s:%sttfragmentsContent-Lengths Content-TypesTransfer-EncodingtCookietstreamttimeouttverifytcerttproxiestallow_redirectsN(sContent-Lengths Content-TypesTransfer-Encoding(.R?RturlRQtcopytappendthistorytcontentRRt RuntimeErrortrawtreadRFtlent max_redirectsRtcloset startswithRRDt_replacetgeturltnetlocRRtrebuild_methodt status_codeR!ttemporary_redirecttpermanent_redirectR;tpopR$tbodytKeyErrorR t_cookiesR tcookiestprepare_cookiestrebuild_proxiest rebuild_autht_body_positionR tsend(R=R>treqRSRTRURVRWtyield_requeststadapter_kwargsthistRYtprevious_fragmenttprepared_requestt parsed_rurltparsedtpurged_headerstheaderR;t rewindable((srequests/sessions.pytresolve_redirects�s|                   cCs{|j}|j}d|kr@|j|jj|ƒr@|d=n|jrUt|ƒnd}|dk rw|j|ƒndS(sé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. t AuthorizationN(R;RYRNtrequestt trust_envRR$t prepare_auth(R=R{R1R;RYtnew_auth((srequests/sessions.pyRss  $  c Cs5|dk r|ni}|j}|j}t|ƒj}|jƒ}|jdƒ}t|d|ƒ}|jr¿| r¿t |d|ƒ} | j|| jdƒƒ} | r¿|j || ƒq¿nd|krÕ|d=nyt ||ƒ\} } Wnt k rd\} } nX| r1| r1t | | ƒ|d>> 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') R;RptauthRWthookstparamsRURVtprefetchtadaptersRSR„RbcCs¥tƒ|_d|_i|_tƒ|_i|_t|_ t |_ d|_ t |_t |_tiƒ|_tƒ|_|jdtƒƒ|jdtƒƒdS(Nshttps://shttp://(RR;R$RšRWRR›RœRFRSRCRURVRRbR„RRpRRžtmountR(R=((srequests/sessions.pyt__init__ms           cCs|S(N((R=((srequests/sessions.pyt __enter__¤scGs|jƒdS(N(Rc(R=targs((srequests/sessions.pyt__exit__§scCs*|jp i}t|tjƒs0t|ƒ}ntttƒ|jƒ|ƒ}|j}|jrƒ| rƒ|j rƒt |j ƒ}nt ƒ}|j d|j jƒd|j d|jd|jd|jdt|j|jdtƒdt|j|jƒd t||jƒd |d t|j|jƒƒ |S( s‹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 R“RYtfilestdatatjsonR;R*RœRšRpR›(RpR%Rt CookieJarRR R RšR„RRYR tprepareR“tupperR¤R¥R¦R0R;RRœR5R›(R=RƒRptmerged_cookiesRštp((srequests/sessions.pytprepare_requestªs*        cCsÇtd|jƒd|d|d|d|p-id|d|p?id|d |d | ƒ }|j|ƒ}| poi} |j|j| | ||ƒ}i| d 6| d 6}|j|ƒ|j||�}|S( sConstructs 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“RYR;R¤R¥R¦RœRšRpR›RTRX(R R©R¬tmerge_environment_settingsRYR&Ru(R=R“RYRœR¥R;RpR¤RšRTRXRWR›RSRURVR¦Rvtpreptsettingst send_kwargsR>((srequests/sessions.pyRƒÒs*)       cKs#|jdtƒ|jd||�S(så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 RXR‘(R‰RCRƒ(R=RYtkwargs((srequests/sessions.pyR2scKs#|jdtƒ|jd||�S(sé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 RXtOPTIONS(R‰RCRƒ(R=RYR±((srequests/sessions.pytoptions$scKs#|jdtƒ|jd||�S(sæ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 RXR�(R‰RFRƒ(R=RYR±((srequests/sessions.pythead/scKs|jd|d|d||�S(sÈ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ƒ(R=RYR¥R¦R±((srequests/sessions.pytpost:s cKs|jd|d||�S(suSends 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 tPUTR¥(Rƒ(R=RYR¥R±((srequests/sessions.pytputGs cKs|jd|d||�S(swSends 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 tPATCHR¥(Rƒ(R=RYR¥R±((srequests/sessions.pytpatchSs cKs|jd||�S(sè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 tDELETE(Rƒ(R=RYR±((srequests/sessions.pytdelete_sc Ks|jd|jƒ|jd|jƒ|jd|jƒ|jd|jƒt|tƒrjtdƒ‚n|jdt ƒ}|j dƒ}|j }|j d|j ƒ}tƒ}|j||�}tƒ|} td| ƒ|_td |||�}|jr1x-|jD]} t|j| j| jƒq Wnt|j||jƒ|j|||�} |r{g| D]} | ^qing} | r¯| jd |ƒ| jƒ}| |_n|sôy(t|j||d t |�ƒ|_Wqôtk rðqôXn|s|jn|S( sISend a given PreparedRequest. :rtype: requests.Response RSRURVRWs#You can only send PreparedRequests.RXRYtsecondsR1iRw(R‰RSRURVRWR%R t ValueErrorRlRCR2R›t get_adapterRYtpreferred_clockRuRtelapsedRR\R RpRƒR_R�tinserttnextt_nextt StopIterationR]( R=RƒR±RXRSR›tadaptertstarttrRÀR>tgenR\((srequests/sessions.pyRuisB     %  (  c Cs|jr«|dk r$|jdƒnd}t|d|ƒ}x*|jƒD]\}} |j|| ƒqIW|tks�|dkr«tjjdƒp¢tjjdƒ}q«nt ||j ƒ}t ||j ƒ}t ||j ƒ}t ||j ƒ}i|d6|d6|d6|d6S( s^ Check the environment and merge it with some settings. :rtype: dict R‡tREQUESTS_CA_BUNDLEtCURL_CA_BUNDLERURWRSRVN(R„R$R2RR'R‰RCtostenvironR0RWRSRURV( R=RYRWRSRURVR‡t env_proxiesR,R-((srequests/sessions.pyR­²s !cCsSx<|jjƒD]+\}}|jƒj|jƒƒr|SqWtd|ƒ‚dS(s~ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter s*No connection adapters were found for '%s'N(RžR'tlowerRdR(R=RYtprefixRÅ((srequests/sessions.pyR¾ÏscCs(x!|jjƒD]}|jƒqWdS(s+Closes all adapters and as such the sessionN(RžtvaluesRc(R=R-((srequests/sessions.pyRcÝscCso||j|îs (t __attrs__(R=tstate((R=srequests/sessions.pyt __getstate__íscCs1x*|jƒD]\}}t|||ƒq WdS(N(R'tsetattr(R=RÖRÔtvalue((srequests/sessions.pyt __setstate__ñsN(R—R˜t__doc__RÕR R¡R£R¬R$RCRƒR2R³R´RµR·R¹R»RuR­R¾RcRŸR×RÚ(((srequests/sessions.pyR™Ts2  7   ) D  I    cCstƒS(sZ 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™(((srequests/sessions.pytsessionös (>RÛRËtsysttimetdatetimeRRšRtcompatRRRRRRRpRR R R tmodelsR R RR›RRt_internal_utilsRtutilsRRRt exceptionsRRRRt structuresRRžRRRRRRR t status_codesR!R"tplatformt perf_counterR¿tAttributeErrortclockR0R5tobjectR6R™RÜ(((srequests/sessions.pyt s:   ."".     õÿ£