o {nhH@sdZddlZddlZddlZddlmZddlmZmZm Z m Z m Z zddl Z Wn e y5ddlZ YnwGdddZGdd d Zd d Zd d ZdddZGdddeZGddde jeZddZddZddZd ddZddZdS)!z requests.cookies ~~~~~~~~~~~~~~~~ Compatibility code to be able to use `http.cookiejar.CookieJar` with requests. requests.utils imports from here, so be careful with imports. N)to_native_string)MorselMutableMapping cookieliburlparse urlunparsec@seZdZdZddZddZddZdd Zd d Zd d Z ddZ dddZ ddZ ddZ ddZeddZeddZeddZdS) MockRequestaWraps a `requests.Request` to mimic a `urllib2.Request`. The code in `http.cookiejar.CookieJar` expects this interface in order to correctly manage cookie policies, i.e., determine whether a cookie can be set, given the domains of the request and the cookie. The original request object is read-only. The client is responsible for collecting the new headers via `get_new_headers()` and interpreting them appropriately. You probably want `get_cookie_header`, defined below. cCs ||_i|_t|jjj|_dSN)_r _new_headersrurlschemetype)selfrequestr;/usr/local/lib/python3.10/dist-packages/requests/cookies.py__init__#szMockRequest.__init__cC|jSr )rrrrrget_type(zMockRequest.get_typecCst|jjjSr )rr r netlocrrrrget_host+zMockRequest.get_hostcC|Sr rrrrrget_origin_req_host.szMockRequest.get_origin_req_hostcCsT|jjds |jjSt|jjddd}t|jj}t|j||j|j |j |j gS)NHostzutf-8)encoding) r headersgetr rrrrpathparamsqueryfragment)rhostparsedrrr get_full_url1s zMockRequest.get_full_urlcCsdSNTrrrrris_unverifiableEszMockRequest.is_unverifiablecCs||jjvp ||jvSr )r r!r rnamerrr has_headerHszMockRequest.has_headerNcCs|jj||j||Sr )r r!r"r )rr-defaultrrr get_headerKszMockRequest.get_headercCstd)zMcookiejar has no legitimate use for this method; add it back if you find one.z=Cookie headers should be added with add_unredirected_header())NotImplementedError)rkeyvalrrr add_headerNszMockRequest.add_headercCs||j|<dSr r rr-valuerrradd_unredirected_headerTrz#MockRequest.add_unredirected_headercCrr r5rrrrget_new_headersWrzMockRequest.get_new_headerscCrr )r+rrrr unverifiableZzMockRequest.unverifiablecCrr )rrrrrorigin_req_host^r;zMockRequest.origin_req_hostcCrr rrrrrr'br;zMockRequest.hostr )__name__ __module__ __qualname____doc__rrrrr)r+r.r0r4r8r9propertyr:r<r'rrrrr s&    r c@s(eZdZdZddZddZddZdS) MockResponsezWraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. ...what? Basically, expose the parsed HTTP headers from the server response the way `http.cookiejar` expects to see them. cCs ||_dS)zMake a MockResponse for `cookiejar` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers N_headers)rr!rrrrns zMockResponse.__init__cCrr rCrrrrinfourzMockResponse.infocCs|j|dSr )rD getheadersr,rrrrFxszMockResponse.getheadersN)r=r>r?r@rrErFrrrrrBgs  rBcCs8t|dr|js dSt|}t|jj}|||dS)zExtract the cookies from the response into a CookieJar. :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object _original_responseN)hasattrrGr rBmsgextract_cookies)jarrresponsereqresrrrextract_cookies_to_jar|s  rOcCs t|}|||dS)zj Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str Cookie)r add_cookie_headerr9r")rKrrrrrget_cookie_headers rScCszg}|D]'}|j|kr q|dur||jkrq|dur ||jkr q||j|j|jfq|D] \}}}||||q.dS)zkUnsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). N)r-domainr#appendclear) cookiejarr-rTr# clearablescookierrrremove_cookie_by_names rZc@seZdZdZdS)CookieConflictErrorzThere are two cookies that meet the criteria specified in the cookie jar. Use .get and .set and include domain and path args in order to be more specific. N)r=r>r?r@rrrrr[sr[cseZdZdZd3ddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZd4ddZfddZddZdd Zd!d"Zfd#d$Zfd%d&Zd4d'd(Zd4d)d*Zd+d,Zd-d.Zd/d0Zd1d2ZZS)5RequestsCookieJaraCompatibility class; is a http.cookiejar.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Requests does not use the dict interface internally; it's just for compatibility with external client code. All requests code should work out of the box with externally provided instances of ``CookieJar``, e.g. ``LWPCookieJar`` and ``FileCookieJar``. Unlike a regular CookieJar, this class is pickleable. .. warning:: dictionary operations that are normally O(1) may be O(n). NcCs(z||||WSty|YSw)zDict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). )_find_no_duplicatesKeyError)rr-r/rTr#rrrr"s  zRequestsCookieJar.getcKs\|durt|||d|dddSt|trt|}n t||fi|}|||S)zDict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. NrTr#)rTr#)rZr" isinstancermorsel_to_cookie create_cookie set_cookie)rr-r7kwargscrrrsets   zRequestsCookieJar.setcct|D]}|jVqdS)zDict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems(). N)iterr-rrYrrriterkeys  zRequestsCookieJar.iterkeyscC t|S)zDict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items(). )listrirrrrkeys zRequestsCookieJar.keysccrf)zDict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems(). N)rgr7rhrrr itervaluesrjzRequestsCookieJar.itervaluescCrk)zDict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items(). )rlrorrrrvaluesrnzRequestsCookieJar.valuesccs"t|D] }|j|jfVqdS)zDict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues(). N)rgr-r7rhrrr iteritemss zRequestsCookieJar.iteritemscCrk)zDict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values(). )rlrqrrrritems s zRequestsCookieJar.itemscC,g}t|D] }|j|vr||jq|S)z2Utility method to list all the domains in the jar.rgrTrUrdomainsrYrrr list_domains    zRequestsCookieJar.list_domainscCrs)z0Utility method to list all the paths in the jar.)rgr#rU)rpathsrYrrr list_pathsrxzRequestsCookieJar.list_pathscCs<g}t|D]}|jdur|j|vrdS||jqdS)zvReturns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool NTFrtrurrrmultiple_domains%s  z"RequestsCookieJar.multiple_domainscCsFi}t|D]}|dus|j|kr |dus|j|kr |j||j<q|S)zTakes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. :rtype: dict N)rgrTr#r7r-)rrTr# dictionaryrYrrrget_dict2s  zRequestsCookieJar.get_dictcs$zt|WStyYdSwr*)super __contains__r[r, __class__rrrAs  zRequestsCookieJar.__contains__cCs ||S)zDict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1). )r]r,rrr __getitem__Gs zRequestsCookieJar.__getitem__cCs|||dS)zDict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead. N)rer6rrr __setitem__PszRequestsCookieJar.__setitem__cCst||dS)zqDeletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s ``remove_cookie_by_name()``. N)rZr,rrr __delitem__WszRequestsCookieJar.__delitem__csNt|jdr|jdr|jdr|jdd|_tj|g|Ri|S)N startswith"z\")rHr7rendswithreplacer~rb)rrYargsrcrrrrb]s   zRequestsCookieJar.set_cookiecs:t|tjr|D] }|t|qdSt|dS)zAUpdates this jar with cookies from another CookieJar or dict-likeN)r_r CookieJarrbcopyr~update)rotherrYrrrrfs zRequestsCookieJar.updatecCs`t|D]}|j|kr"|dus|j|kr"|dus|j|kr"|jSqtd|d|d|)aRequests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value Nname= , domain=, path=)rgr-rTr#r7r^)rr-rTr#rYrrr_findns  zRequestsCookieJar._findcCs~d}t|D]'}|j|kr-|dus|j|kr-|dus|j|kr-|dur*td||j}q|r2|Std|d|d|)aBoth ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value Nz&There are multiple cookies with name, rrr)rgr-rTr#r[r7r^)rr-rTr#toReturnrYrrrr]s  z%RequestsCookieJar._find_no_duplicatescCs|j}|d|S)4Unlike a normal CookieJar, this class is pickleable. _cookies_lock)__dict__rpoprstaterrr __getstate__s  zRequestsCookieJar.__getstate__cCs(|j|d|jvrt|_dSdS)rrN)rr threadingRLockrrrrr __setstate__s  zRequestsCookieJar.__setstate__cCs"t}|||||S)z(Return a copy of this RequestsCookieJar.)r\ set_policy get_policyr)rnew_cjrrrrs zRequestsCookieJar.copycCr)z&Return the CookiePolicy instance used.)_policyrrrrrszRequestsCookieJar.get_policy)NNNNN)r=r>r?r@r"rerirmrorprqrrrwrzr{r}rrrrrbrrr]rrrr __classcell__rrrrr\s4           r\cCsN|durdSt|dr|St|}||D] }|t|q|S)Nr)rHrrVrb)rKnew_jarrYrrr_copy_cookie_jars  rcKsd||ddddddddddidd }t|t|}|r%td t|||t|d |d <t|d |d <|d d|d<t|d|d<tjdi|S)zMake a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). rNr/FTHttpOnly) versionr-r7portrTr#secureexpiresdiscardcomment comment_urlrestrfc2109z2create_cookie() got unexpected keyword arguments: rport_specifiedrTdomain_specified.domain_initial_dotr#path_specifiedr)re TypeErrorrlrboolrrrP)r-r7rcresultbadargsrrrras2  racCsd}|dr&zttt|d}Wn"ty%td|ddw|dr7d}tt|d|}t|dt|dd|d ||j |d dd |d idt|d |j |dp]dd S)zBConvert a Morsel object into a Cookie containing the one k/v pair.Nzmax-agez max-age: z must be integerrz%a, %d-%b-%Y %H:%M:%S GMTrFrTr#rhttponlyrrr) rrrrTrr-r#rrrrr7r) inttime ValueErrorrcalendartimegmstrptimerarr2r7)morselr time_templaterrrr`s2     r`TcCsR|durt}|dur'dd|D}|D]}|s||vr&|t|||q|S)aCReturns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. :rtype: CookieJar NcSsg|]}|jqSr)r-).0rYrrr sz'cookiejar_from_dict..)r\rbra) cookie_dictrW overwritenames_from_jarr-rrrcookiejar_from_dict s  rcCszt|tjs tdt|trt||dd}|St|tjr;z||W|Sty:|D]}||q/Y|Sw|S)zAdd cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar z!You can only merge into CookieJarF)rWr) r_rrrdictrrAttributeErrorrb)rWcookies cookie_in_jarrrr merge_cookiess      rrr*)r@rrr_internal_utilsrcompatrrrrrr ImportErrordummy_threadingr rBrOrSrZ RuntimeErrorr[rr\rrar`rrrrrrs2     P  %