a Ym@sdZddlZddlZddlZddlmZddlmZddlm 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)ddl*m+Z+ddlm,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2m3Z3ddlm4Z4dZ5e6dkrbz ej7Z8Wne9y^ej:Z8Yn0nejZ8e fddZ;e fddZGddde>Z?ddZ@dS) z requests.session ~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). N)Mapping) timedelta)_basic_auth_str) cookielibis_py3 OrderedDicturljoinurlparse)cookiejar_from_dictextract_cookies_to_jarRequestsCookieJar merge_cookies)RequestPreparedRequestDEFAULT_REDIRECT_LIMIT) default_hooks dispatch_hook)to_native_string)to_key_val_listdefault_headers)TooManyRedirects InvalidSchemaChunkedEncodingErrorContentDecodingError)RecentlyUsedContainer)CaseInsensitiveDict) HTTPAdapter) requote_uriget_environ_proxiesget_netrc_authshould_bypass_proxiesget_auth_from_url rewind_body)codes)REDIRECT_STATIiWindowscCsp|dur |S|dur|St|tr,t|ts0|S|t|}|t|dd|D}|D] }||=q`|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` NcSsg|]\}}|dur|qSN).0kvr(r(8/Users/ymaher/Downloads/lambdas_org/requests/sessions.py Mz!merge_setting..) isinstancerrupdateitems)Zrequest_settingZsession_setting dict_classZmerged_settingZ none_keyskeyr(r(r, merge_setting5s r4cCs@|dus|dgkr|S|dus0|dgkr4|St|||S)zProperly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. Nresponse)getr4)Z request_hooksZ session_hooksr2r(r(r, merge_hooksTs r7c@s6eZdZddZdddZdd Zd d Zd d ZdS)SessionRedirectMixincCs,|jr(|jd}tr|d}t|dSdS)z7Receives a Response. Returns a redirect URI or ``None``locationlatin1utf8N) is_redirectheadersrencoder)selfrespr9r(r(r,get_redirect_targetes    z(SessionRedirectMixin.get_redirect_targetFNTc ks6g} ||} | r2|} | || dd|_z |jWn&tttfyd|jj ddYn0t |j|j krt d|j |d| | drt|j} dt| j| f} t| } | } | jst|jt| } nt| } t| | _|jr|j| jkr| j|j|j<|| ||jtjtjfvrXd }|D]}| j|dq>> 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=reauthrJhooksparamsrHrIZprefetchadaptersrFrsrTcCs|t|_d|_i|_t|_i|_d|_d|_d|_ t |_ d|_ t i|_t|_|dt|dttt|_dS)NFTzhttps://zhttp://)rr=rrJrrrrFrHrIrrTrsr rerrmountrrREDIRECT_CACHE_SIZEr\r?r(r(r,__init__Ps zSession.__init__cCs|Sr'r(rr(r(r, __enter__szSession.__enter__cGs |dSr')rU)r?argsr(r(r,__exit__szSession.__exit__c Cs|jpi}t|tjst|}ttt|j|}|j}|jrR|sR|jsRt |j }t }|j |j |j |j|j|jt|j|jtdt|j|jt||j|t|j|jd |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 )r2) rrWfilesdatajsonr=rrrer)rer/r CookieJarr rr rrsr rWrpreparerupperrrrr4r=rrr7r)r?rqreZmerged_cookiesrpr(r(r,prepare_requests.       zSession.prepare_requestNTc Csxt|||||pi||pi||| d }||}| p8i} ||j| | ||}| | d}|||j|fi|}|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, 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 ) rrWr=rrrrrrer)rGrK)rrrmerge_environment_settingsrWr0rj)r?rrWrrr=rerrrGrKrJrrFrHrIrrkprepsettingsZ send_kwargsr@r(r(r,rqs.4   zSession.requestcKs |dd|jd|fi|S)zSends 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 rKTr~ryrqr?rWkwargsr(r(r,r6 s z Session.getcKs |dd|jd|fi|S)zSends 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 rKTOPTIONSrrr(r(r,optionss zSession.optionscKs |dd|jd|fi|S)zSends 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 rKFr}rrr(r(r,head s z Session.headcKs|jd|f||d|S)aSends 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)rrrq)r?rWrrrr(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 PUTrrr?rWrrr(r(r,put7s 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 PATCHrrrr(r(r,patchBs z Session.patchcKs|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 DELETErrr(r(r,deleteMszSession.deletecKs|d|j|d|j|d|j|d|jt|trJtd|dd}| d}|j }|rt }|j |j vr||j |j |j }||vrq||_ qp|j|j d}t} |j|fi|} t| } t| d | _td || fi|} | jr | jD]} t|j| j| jqt|j|| j|j| |fi|} |rXd d | Dng}|r||d | |} || _|s| j| S)zR Send a given PreparedRequest. :rtype: requests.Response rFrHrIrJz#You can only send PreparedRequests.rKT)rW)secondsr5cSsg|]}|qSr(r()r)r@r(r(r,r-r.z Session.send..r)ryrFrHrIrJr/r ValueErrorrar6rsetrWr\add get_adapterpreferred_clockrjrelapsedrrNr rerqrQroinsertrO)r?rqrrKrFrZ checked_urlsnew_urladapterstartrrr@genrNr(r(r,rjWsH         z Session.sendc Cs|jrn|dur|dnd}t||d}|D]\}} ||| q0|dusV|durntjdpltjd}t||j}t||j }t||j }t||j }||||dS)z^ Check the environment and merge it with some settings. :rtype: dict NrvrwTREQUESTS_CA_BUNDLEZCURL_CA_BUNDLE)rHrJrFrI) rsr6rr1ryosenvironr4rJrFrHrI) r?rWrJrFrHrIrvZ env_proxiesr*r+r(r(r,rs        z"Session.merge_environment_settingscCs:|jD]\}}||r |Sq td|dS)z~ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter z*No connection adapters were found for '%s'N)rr1lowerrVr)r?rWprefixrr(r(r,rs zSession.get_adaptercCs|jD] }|q dS)z+Closes all adapters and as such the sessionN)rvaluesrU)r?r+r(r(r,rUsz Session.closecs>||j<fdd|jD}|D]}|j||j|<q"dS)ztRegisters a connection adapter to a prefix. Adapters are sorted in descending order by key length. cs g|]}t|tkr|qSr()rS)r)r*rr(r,r-r.z!Session.mount..N)rra)r?rrZ keys_to_mover3r(rr,rs z Session.mountcs*tfddjD}tj|d<|S)Nc3s|]}|t|dfVqdSr')getattr)r)attrrr(r, r.z'Session.__getstate__..r\)dict __attrs__r\)r?stater(rr, __getstate__szSession.__getstate__cCsT|di}|D]\}}t|||qtt|_|D]\}}||j|<qsF             U: