3 gY G @sdZddlZddlZddlZddlZddlmZddlmZm Z m Z m Z y ddl Z Wne k rpddlZ YnXGdddeZGdd d eZd d Zd d ZdddZGdddeZGdddejejZddZddZddZd 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 urlunparseMorselc@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|_dS)N)_r _new_headersrurlschemetype)selfrequestrA/Users/olari/OneDrive/sandbox/awsBlog2/lambda/requests/cookies.py__init__&szMockRequest.__init__cCs|jS)N)r )rrrrget_type+szMockRequest.get_typecCst|jjjS)N)rr r netloc)rrrrget_host.szMockRequest.get_hostcCs|jS)N)r)rrrrget_origin_req_host1szMockRequest.get_origin_req_hostcCsT|jjjds|jjSt|jjddd}t|jj}t|j||j|j |j |j gS)NHostzutf-8)encoding) r headersgetr rrrr pathparamsqueryfragment)rhostparsedrrr get_full_url4s zMockRequest.get_full_urlcCsdS)NTr)rrrris_unverifiableBszMockRequest.is_unverifiablecCs||jjkp||jkS)N)r rr )rnamerrr has_headerEszMockRequest.has_headerNcCs|jjj||jj||S)N)r rrr )rr#defaultrrr get_headerHszMockRequest.get_headercCs tddS)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()N)NotImplementedError)rkeyvalrrr add_headerKszMockRequest.add_headercCs||j|<dS)N)r )rr#valuerrradd_unredirected_headerOsz#MockRequest.add_unredirected_headercCs|jS)N)r )rrrrget_new_headersRszMockRequest.get_new_headerscCs|jS)N)r")rrrr unverifiableUszMockRequest.unverifiablecCs|jS)N)r)rrrrorigin_req_hostYszMockRequest.origin_req_hostcCs|jS)N)r)rrrrr]szMockRequest.host)N)__name__ __module__ __qualname____doc__rrrrr!r"r$r&r*r,r-propertyr.r/rrrrrrs    rc@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)rrrrrriszMockResponse.__init__cCs|jS)N)r6)rrrrinfopszMockResponse.infocCs|jj|dS)N)r6 getheaders)rr#rrrr8sszMockResponse.getheadersN)r0r1r2r3rr7r8rrrrr5bsr5cCs8t|do|jsdSt|}t|jj}|j||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)hasattrr9rr5msgextract_cookies)jarrresponsereqresrrrextract_cookies_to_jarws   rAcCs t|}|j||jjdS)zj Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str Cookie)radd_cookie_headerr-r)r=rrrrrget_cookie_headers rEcCsg}xV|D]N}|j|krq |dk r.||jkr.q |dk rB||jkrBq |j|j|j|jfq Wx |D]\}}}|j|||qbWdS)zkUnsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). N)r#domainrappendclear) cookiejarr#rFr clearablescookierrrremove_cookie_by_names  rLc@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)r0r1r2r3rrrrrMsrMcseZdZdZd1ddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZd2ddZfddZddZdd Zd!d"Zfd#d$Zfd%d&Zd3d'd(Zd4d)d*Zd+d,Zd-d.Zd/d0ZZS)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). Nc Cs(y|j|||Stk r"|SXdS)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). N)_find_no_duplicatesKeyError)rr#r%rFrrrrrszRequestsCookieJar.getcKsX|dkr(t|||jd|jdddSt|trg}x4t|D](}|jdk r*|j|kr*dS|j|jqWdS)zvReturns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool NTF)rXrFrG)rr`rKrrrmultiple_domainss z"RequestsCookieJar.multiple_domainscCsJi}x@t|D]4}|dks$|j|kr|dks6|j|kr|j||j<qW|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)rXrFrr+r#)rrFr dictionaryrKrrrget_dict,s zRequestsCookieJar.get_dictc s*ytt|j|Stk r$dSXdS)NT)superrN __contains__rM)rr#) __class__rrrh<szRequestsCookieJar.__contains__cCs |j|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). )rO)rr#rrr __getitem__BszRequestsCookieJar.__getitem__cCs|j||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)rW)rr#r+rrr __setitem__KszRequestsCookieJar.__setitem__cCst||dS)zlDeletes a cookie given a name. Wraps ``cookielib.CookieJar``'s ``remove_cookie_by_name()``. N)rL)rr#rrr __delitem__RszRequestsCookieJar.__delitem__csLt|jdr4|jjdr4|jjdr4|jjdd|_tt|j|f||S)N startswith"z\")r:r+rmendswithreplacergrNrT)rrKargsrU)rirrrTXs$zRequestsCookieJar.set_cookiecs@t|tjr,x.|D]}|jtj|qWntt|j|dS)zAUpdates this jar with cookies from another CookieJar or dict-likeN)rQr CookieJarrTcopyrgrNupdate)rotherrK)rirrru]s  zRequestsCookieJar.updatecCs\xDt|D]8}|j|kr |dks*|j|kr |dks<|j|kr |jSq Wtd|||fdS)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 Nzname=%r, domain=%r, path=%r)rXr#rFrr+rP)rr#rFrrKrrr_findes   zRequestsCookieJar._findcCs|d}xXt|D]L}|j|kr|dks.|j|kr|dks@|j|kr|dk rTtd||j}qW|rf|Std|||fdS)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, %rzname=%r, domain=%r, path=%r)rXr#rFrrMr+rP)rr#rFrtoReturnrKrrrrOys    z%RequestsCookieJar._find_no_duplicatescCs|jj}|jd|S)z4Unlike a normal CookieJar, this class is pickleable. _cookies_lock)__dict__rtpop)rstaterrr __getstate__s  zRequestsCookieJar.__getstate__cCs$|jj|d|jkr tj|_dS)z4Unlike a normal CookieJar, this class is pickleable.ryN)rzru threadingRLockry)rr|rrr __setstate__s  zRequestsCookieJar.__setstate__cCst}|j||S)z(Return a copy of this RequestsCookieJar.)rNru)rnew_cjrrrrts zRequestsCookieJar.copy)NNN)NN)NN)NN)r0r1r2r3rrWrYr[r\r]r^r_rarcrdrfrhrjrkrlrTrurwrOr}rrt __classcell__rr)rirrNs0            rNcCsR|dkr dSt|dr|jStj|}|jx|D]}|jtj|q6W|S)Nrt)r:rtrHrT)r=new_jarrKrrr_copy_cookie_jars   rcKstd||ddddddddddidd }t|t|}|rNd }t|t||j|t|d |d <t|d |d <|d jd|d<t|d|d<tjf|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"). rNro/FTHttpOnly) versionr#r+portrFrsecureexpiresdiscardcomment comment_urlrestrfc2109z4create_cookie() got unexpected keyword arguments: %srport_specifiedrFdomain_specified.domain_initial_dotrpath_specified) dictrW TypeErrorrZruboolrmrrB)r#r+rUresultbadargserrrrrrSs0 rScCsd}|drPyttjt|d}Wqrtk rLtd|dYqrXn"|drrd}tjtj|d|}t|dt|dd|d||j |d dd |d idt|d |j |d pdd 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 GMTrFrFrrhttponlyrrr) rrrrFrr#rrrrrr+r) inttime ValueErrorrcalendartimegmstrptimerSrr(r+)morselr time_templaterrrrRs0   rRTcCsV|dkrt}|dk rRdd|D}x,|D]$}|s:||kr*|jt|||q*W|S)a-Returns 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. NcSsg|] }|jqSr)r#).0rKrrr sz'cookiejar_from_dict..)rNrTrS) cookie_dictrI overwritenames_from_jarr#rrrcookiejar_from_dicts  rc Cszt|tjstdt|tr.t||dd}nHt|tjrvy|j|Wn,tk rtx|D]}|j|q^WYnX|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. z!You can only merge into CookieJarF)rIr) rQrrsrrrruAttributeErrorrT)rIcookies cookie_in_jarrrr merge_cookies s    r)NN)NT)r3rtrr collections_internal_utilsrcompatrrrrr~ ImportErrordummy_threadingobjectrr5rArErL RuntimeErrorrMrsMutableMappingrNrrSrRrrrrrr s.  H {#