7,jȅdZddlmZddlZddlZddlZddlmZddlm Z m Z m Z ddl m Z ddlmZmZmZdd lmZdd lmZdd lmZdd lmZdd lmZmZmZddlm Z m!Z!m"Z"m#Z#ddl$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*m+Z+ddl,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2m3Z3ddl4m5Z5ddl6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@erddlAmBZBddlCmDZDmEZEddlFmZGddlmHZHejIdkrejJZKnejZKefd*d ZLefd+d$ZMGd%d&ZNGd'd(eNZOd,d)ZPdS)-z requests.sessions ~~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). ) annotationsN) OrderedDict) GeneratorMappingMutableMapping) timedelta) TYPE_CHECKINGAnycast)to_native_string) is_prepared) HTTPAdapter)_basic_auth_str) cookieliburljoinurlparse)RequestsCookieJarcookiejar_from_dictextract_cookies_to_jar merge_cookies)ChunkedEncodingErrorContentDecodingError InvalidSchemaTooManyRedirects) default_hooks dispatch_hook)DEFAULT_REDIRECT_LIMITREDIRECT_STATIPreparedRequestRequestResponse)codes)CaseInsensitiveDict) DEFAULT_PORTSdefault_headersget_auth_from_urlget_environ_proxiesget_netrc_auth requote_uriresolve_proxies rewind_bodyshould_bypass_proxiesto_key_val_list) CookieJar)SelfUnpack)_types) BaseAdapterwin32request_settingr session_setting dict_classtypereturnc.||S||St|trt|ts|S|t|}|t|d|D}|D]}||=|S)zDetermines 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` Ncg|] \}}|| SN).0kvs AC:\PYTHON\GemmaClient\venv\Lib\site-packages\requests/sessions.py z!merge_setting..esEEEv119999) isinstancerr.updateitems)r5r6r7merged_setting none_keyskeys rA merge_settingrJLs ?G,,1;OW1U1UZ @ @AAN//::;;;FE!5!5!7!7EEEI   3   rC request_hooks _t.HooksType session_hooksc||dgkr|S||dgkr|St|||S)zProperly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. Nresponse)getrJ)rKrMr7s rA merge_hooksrQls^ 1 1* = = C C 1 1* = = C C  z B BBrCcteZdZUded<ded<ded<d-d Zd.dZd/dZ d0d1d%Zd2d)Zd3d+Z d2d,Z dS)4SessionRedirectMixinint max_redirectsbool trust_envrcookiesrequestr kwargsr r9r"c dSr<r=)selfrYrZs rAsendzSessionRedirectMixin.sendsrCresp str | Nonecx|jr2|jd}|d}t|dSdS)z7Receives a Response. Returns a redirect URI or ``None``locationlatin1utf8N) is_redirectheadersencoder )r\r^ras rAget_redirect_targetz(SessionRedirectMixin.get_redirect_targetsC   6|J/H x00H#Hf55 5trCold_urlstrnew_urlcbt|}t|}|j|jkrdS|jdkr|jdvr|jdkr |jdvrdS|j|jk}|j|jk}t j|jddf}|s|j|vr |j|vrdS|p|S)zFDecide whether Authorization header should be removed when redirectingThttp)PNhttps)iNFN)rhostnameschemeportr%rP)r\rhrj old_parsed new_parsed changed_portchanged_scheme default_ports rAshould_strip_authz&SessionRedirectMixin.should_strip_authsg&& g&&  *"5 5 54   ' ':--!W,,;..5"*/9 #*j.??%)**;TBBDI  <//<//5-~-rCFNTreqstreamtimeout_t.TimeoutTypeverify _t.VerifyTypecert _t.CertTypeproxiesdict[str, str] | Noneyield_requestsadapter_kwargsGenerator[Response, None, None]c +Kg} ||} t|jj} | r-|} | dd|_| | |jn8#tttf$r|j dYnwxYwt|j|jkrtd|jd||| dr=t|j}dt'|j| g} t| }|jd kr| r|| }n|jr|j} |} |js#t1|jt3| } nt3| } t'| | _|| ||jt8jt8jfvr)d }|D]}| j |dd| _!| j}| d dtEd | j#}tI|||j tK||j&| '||(| |}|)| || j*duod|vpd|v}|rtW| | }|r|VnI|j,|f|||||dd| }tI|j&| |j ||} |V| +dSdS)zBReceives a Response. Returns a generator of Responses or Requests.NF)decode_contentz Exceeded z redirects.)rOz//:)fragment)Content-Lengthz Content-TypeTransfer-EncodingCookier/rr)ryrzr|r~rallow_redirects)-rgrurlrcopyhistoryappendcontentrr RuntimeErrorrawreadlenrUrclose startswithjoinr rp_replacegeturlnetlocrr*rebuild_method status_coder#temporary_redirectpermanent_redirectrepopbodyr _cookiesrrrXprepare_cookiesrebuild_proxies rebuild_auth_body_positionr,r])r\r^rxryrzr|r~rrrhistrprevious_fragmentprepared_request parsed_rurlparsedpurged_headersheaderre cookie_jar rewindables rAresolve_redirectsz&SessionRedirectMixin.resolve_redirectss "&&t,,$SW--6g "xxzz  7DL KK    4 (*> M 4 4 4 U 33333 44<  D$666&? 2???$ JJLLL~~d## L&tx00 hh 01C D DcJKKc]]F"$$):$2CDD 4$*O!--//C = 'dh C(8(899!#&&#3C#8#8     0$ 7 7 7((( "Y,??F$,00>>>>(, %&.G KK$ ' ' ' k+;+DEEJ ":sDH = = = *dl 3 3 3  , ,Z 8 8 8**+;WEEG   . 5 5 5 *8D G+M/Bg/M   .,---#C   ty !#!#$)  %  't|5EtxPPP..t44 Og g g g g s/A772B,+B,rrONonec|j}t|sJt|sJ|j}|j}|j}d|vr|||r|d=|jrt |nd}|||dSdS)zWhen 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)rY _is_preparedrerrwrWr) prepare_auth)r\rrOoriginal_requestre original_urlrnew_auths rArz!SessionRedirectMixin.rebuild_auth5s$+,-----,-----"*'+ " g % %$*@*@s*S*S %(+/.B>#&&&d    ) )( 3 3 3 3 3 rCdict[str, str]cXt|sJ|j}t|jj}t |||j}d|vr|d= t||\}}n#t$rd\}}YnwxYw| ds|r|rt|||d<|S)aThis 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-AuthorizationNNrn) rrerrrpr+rWr'KeyErrorrr)r\rrrerp new_proxiesusernamepasswords rArz$SessionRedirectMixin.rebuild_proxiesNs ,-----"**.//6%&6PP G + +-. ,!2;v3F!G!G Hhh , , ,!+ Hhhh ,   )) Qh Q8 Q->> 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') zCaseInsensitiveDict[str]re _t.AuthTypeauthrrzdict[str, list[_t.HookType]]hookszMutableMapping[str, Any]paramsrVryr}r|rr~rTrUrWrrXz MutableMapping[str, BaseAdapter]adapters) rerXrrrrr|r~rryrWrUz list[str] __attrs__r9rct|_d|_i|_t |_i|_d|_d|_d|_ t|_ d|_ ti|_t|_|dt%|dt%dS)NFTzhttps://zhttp://)r&rerrrrrryr|r~rrUrWrrXrrmountrr\s rA__init__zSession.__init__s'((   #__     4 +2.. $   :{}}--- 9kmm,,,,,rCr0c|Sr<r=rs rA __enter__zSession.__enter__s rCargsr c.|dSr<)r)r\rs rA__exit__zSession.__exit__s rCrYr!r ctd|j}tt|j}|jpi}t |t jst|}ttt|j|}|j }|j r|s|j st|}t}||||j|j|jt)|j|jt,t)|j|jt)||j |t1|j|j |S)aConstructs 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 _t.UriType)r7) rrfilesdatajsonrerrrXr)r rrirrXrDrr/rrrrrWr)r prepareupperrrrrJrer$rrQr)r\rYrrrXmerged_cookiesrps rAprepare_requestzSession.prepare_requestsM<--c7>**/'R'9#677 3)'22G' +--t| <  '$ 'ty '!#&&D    <<>>-!:M!==tTY//"gmTZ88  rCNTrrirr _t.ParamsTyper _t.DataType_t.HeadersType5RequestsCookieJar | CookieJar | dict[str, str] | Noner _t.FilesTyperzr{rr_t.HooksInputType | None bool | None_t.VerifyType | Noner _t.JsonTyper"c t|tr|d}t|||||pi||pi|||  }||}t |sJ| pi} ||j| | ||}| | d}| ||j |fi|}|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, 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 many seconds 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 hooks: (optional) Dictionary mapping hook name to one event or list of events, event must be callable. :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 zutf-8) rrrerrrrrrXr)rzr) rDbytesdecoder!rrrmerge_environment_settingsrrEr])r\rrrrrerXrrrzrrrryr|r~rrxprepsettings send_kwargsr^s rArYzSession.request-s| c5 ! ! &**W%%C<<>>>t>v>>>rCc  |jd|fi|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. :rtype: requests.Response DELETErrs rAdeletezSession.deletes t|Hc44V444rCc P|d|j|d|j|d|jd|vrt ||j|j|d<t|trtdt|sJ| dd}| d}|j }||j}t!}|j|fi|}t!|z } t%| |_t)d ||fi|}|jr*|jD]"} t-|j| j| j#t-|j||j|r|j||fi|} d | D} ng} | r1| d || }| |_|s5 t9|j||fd di||_n#t<$rYnwxYw|s|j|S)zISend a given PreparedRequest. :rtype: requests.Response ryr|r~rz#You can only send PreparedRequests.rT)r)secondsrOcg|]}|Sr=r=)r>r^s rArBz Session.send..%s,,,t,,,rCrr) rryr|r~r+rrWrDr! ValueErrorrrrPr get_adapterrpreferred_clockr]relapsedrrrrXrYrrinsertnext_next StopIterationr) r\rYrZrryradapterstartrrr^genrs rAr]z Session.sends (DK000(DK000&$),,, F " " /t~ V VF9  gw ' ' DBCC CG$$$$$!**%6==H%% ""w{"33 !! GL + +F + +"##e+g...  *eQ 9 9& 9 9 9 M  M M&t|T\48LLLLt|Wae<<<  ($(G>>v>>C,,,,,GGG  NN1a  AAI  *D*1gUUdUfUU!      IIs)#H HHdict[str, Any]c |jr||dnd}t||}|0|D]\}} ||| |dus|@t jdp t jdp|}t||j}t||j }t||j }t||j }||||dS)z^ Check the environment and merge it with some settings. :rtype: dict Nno_proxy)r$TREQUESTS_CA_BUNDLECURL_CA_BUNDLE)rryr|r~) rWrPr(rFrosenvironrJrryr|r~) r\rrryr|r~r$ env_proxiesr?r@s rArz"Session.merge_environment_settings?s > 292Ew{{:...4H-cHEEEK"'--//--DAq&&q!,,,,~~JNN#788z~~&677 66vt{33vt{33T49--"fPTUUUrCr3c|jD]B\}}||r|cSCt d|)z~ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter z&No connection adapters were found for )rrFlowerrr)r\rprefixrs rArzSession.get_adapterfsr $}2244  OFGyy{{%%fllnn55  LSLLMMMrCcf|jD]}|dS)z+Closes all adapters and as such the sessionN)rvaluesr)r\r@s rArz Session.closess8%%''  A GGIIII  rCr,rc||j<fd|jD}|D]$}|j||j|<%dS)zwRegisters a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. cTg|]$}t|tk"|%Sr=)r)r>r?r,s rArBz!Session.mount..~s/IIIaCFFS[[4H4H4H4H4HrCN)rr)r\r,r keys_to_moverIs ` rArz Session.mountxsd !( fIIII4=III  8 8C!%!2!23!7!7DM#   8 8rCc.fdjD}|S)Nc4i|]}|t|dSr<)getattr)r>attrr\s rA z(Session.__getstate__..s'LLLTwtT400LLLrC)r)r\states` rA __getstate__zSession.__getstate__s#LLLLT^LLL rCr7c\|D]\}}t|||dSr<)rFsetattr)r\r7r5values rA __setstate__zSession.__setstate__s< ;;== ' 'KD% D$ & & & & ' 'rC)r9r)r9r0)rr r9r)rYr!r9r )NNNNNNNTNNNNNN)"rrirrrrrrrerrXrrrrrrzr{rrVrrrrryrr|rr~rrrr9r"r<)rrrrrZrr9r")rrrZrr9r"r) rrrrrrrZrr9r")rrrrrZrr9r"r) rrirrryrr|rr~rr9r")rrir9r3)r,rirr3r9r)r9r")r7r"r9r)rrr__doc__rrrrrrrYrPrrrr rrr]rrrrr8r<r=rCrArrs$&%%%''''$$$$LLLOOO....   I    =-=-=-=-~,,,,d!% "&IM" "& $)-*."'+  #`````J!%AAAAA$ 6 6 6 6 3 3 3 3! IIIII(48 = = = = =48 ? ? ? ? ?5555MMMM^%V%V%V%VN N N N N 8 8 8 8''''''rCrctS)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 )rr=rCrAsessionr?s 99rC)r5r r6r r7r8r9r )rKrLrMrLr7r8r9rL)r9r)Qr= __future__rr'systime collectionsrcollections.abcrrrdatetimertypingr r r _internal_utilsr r2rrrrrrcompatrrrrXrrrr exceptionsrrrrrrrmodelsrrr r!r" status_codesr# structuresr$utilsr%r&r'r(r)r*r+r,r-r.http.cookiejarr/typing_extensionsr0r1r_tr3platform perf_counterrrJrQrSrr?r=rCrArSs#""""" ######>>>>>>>>>>++++++++++------//////!!!!!!!!!!!!0000000000  0/////// ++++++                        &((((((........%%%%%%<7'OOiODOF#CCCCC&I)I)I)I)I)I)I)I)X~'~'~'~'~'"~'~'~'B      rC