o Ba_G@sdZddlZddlZddlZddlmZddlmZmZm Z m Z m Z zddl Z Wn e y5ddlZ YnwGdddeZGdd d eZd d Zd d ZdddZGdddeZGdddeje ZddZddZddZd ddZddZdS)!z requests.cookies ~~~~~~~~~~~~~~~~ Compatibility code to be able to use `cookielib.CookieJar` with requests. requests.utils imports from here, so be careful with imports. N)to_native_string) cookieliburlparse urlunparseMorselMutableMappingc@seZdZdZddZddZddZdd Zd d Zd d Z ddZ dddZ ddZ ddZ ddZeddZeddZeddZdS) MockRequestaWraps a `requests.Request` to mimic a `urllib2.Request`. The code in `cookielib.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)selfrequestr2/usr/lib/python3/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_host0szMockRequest.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_url3s zMockRequest.get_full_urlcCsdSNTrrrrris_unverifiableAszMockRequest.is_unverifiablecCs||jjvp ||jvSr )r r!r rnamerrr has_headerDszMockRequest.has_headerNcCs|jj||j||Sr )r r!r"r )rr-defaultrrr get_headerGszMockRequest.get_headercCstd)zMcookielib 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_headerJzMockRequest.add_headercCs||j|<dSr r rr-valuerrradd_unredirected_headerNrz#MockRequest.add_unredirected_headercCrr r6rrrrget_new_headersQrzMockRequest.get_new_headerscCrr )r+rrrr unverifiableTr5zMockRequest.unverifiablecCrr )rrrrrorigin_req_hostXr5zMockRequest.origin_req_hostcCrr rrrrrr'\r5zMockRequest.hostr )__name__ __module__ __qualname____doc__rrrrr)r+r.r0r4r9r:propertyr;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 `cookielib` expects to see them. cCs ||_dS)zMake a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers N_headers)rr!rrrrhs zMockResponse.__init__cCrr rCrrrrinfoorzMockResponse.infocCs|j|dSr )rD getheadersr,rrrrFrszMockResponse.getheadersN)r=r>r?r@rrErFrrrrrBas  rBcCs8t|dr|js dSt|}t|jj}|||dS)zExtract the cookies from the response into a CookieJar. :param jar: cookielib.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_jarvs  rOcCs t|}|||dS)zj Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str Cookie)r add_cookie_headerr:r")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 cookielib.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-r8kwargscrrrsets   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)rgr8rhrrr 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-r8rhrrr 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(). )rlrqrrrritemss 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_domainss  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#r8r-)rrTr# dictionaryrYrrrget_dict+s  zRequestsCookieJar.get_dictcs(z tt||WStyYdSwr*)superr\ __contains__r[r, __class__rrr;s  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__As 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)rer7rrr __setitem__JszRequestsCookieJar.__setitem__cCst||dS)zlDeletes a cookie given a name. Wraps ``cookielib.CookieJar``'s ``remove_cookie_by_name()``. N)rZr,rrr __delitem__QszRequestsCookieJar.__delitem__csRt|jdr|jdr|jdr|jdd|_tt|j|g|Ri|S)N startswith"z\")rHr8rendswithreplacer~r\rb)rrYargsrcrrrrbWs$zRequestsCookieJar.set_cookiecs>t|tjr|D] }|t|qdStt||dS)zAUpdates this jar with cookies from another CookieJar or dict-likeN)r_r CookieJarrbcopyr~r\update)rotherrYrrrr\s zRequestsCookieJar.updatecCsXt|D]}|j|kr"|dus|j|kr"|dus|j|kr"|jSqtd|||f)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=%r, domain=%r, path=%r)rgr-rTr#r8r^)rr-rTr#rYrrr_findds  zRequestsCookieJar._findcCstd}t|D]&}|j|kr,|dus|j|kr,|dus|j|kr,|dur)td||j}q|r1|Std|||f)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, %rr)rgr-rTr#r[r8r^)rr-rTr#toReturnrYrrrr]xs   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&d }t|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-r8portrTr#secureexpiresdiscardcomment comment_urlrestrfc2109z4create_cookie() got unexpected keyword arguments: %srport_specifiedrTdomain_specified.domain_initial_dotr#path_specifiedr)re TypeErrorrlrboolrrrP)r-r8rcresultbadargserrrrrras0 racCsd}|dr$zttt|d}Wn ty#td|dw|dr5d}tt|d|}t|dt|dd|d||j |d dd |d idt|d |j |d p[dd S)zBConvert a Morsel object into a Cookie containing the one k/v pair.Nzmax-agezmax-age: %s must be integerrz%a, %d-%b-%Y %H:%M:%S GMTrFrTr#rhttponlyrrr) rrrrTrr-r#rrrrr8r) inttime ValueErrorrcalendartimegmstrptimerarr2r8)morselr time_templaterrrr`s6     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_dicts  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_threadingobjectr rBrOrSrZ RuntimeErrorr[rr\rrar`rrrrrrs2     H $