B k×]auã@s¢dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddl mZddlmZddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"dd l#m$Z$dd l%m&Z&dd l'm(Z(m)Z)m*Z*m+Z+d Z,e -¡Z.d ddœZ/ej0dk�r2dd„Z1dd„Zdd„Z2dd„Z3dhdd„Z4dd„Z5dd„Z6d d!„Z7d"d#„Z8d$d%„Z9d&d'„Z:did(d)„Z;d*d+„Zd0d1„Z?d2d3„Z@d4d5„ZAd6d7„ZBd8d9„ZCeDd:ƒZEd;d<„ZFd=d>„ZGd?d@„ZHdAdB„ZIdCdD„ZJdEdF„ZKejLdGdH„ƒZMdIdJ„ZNdjdKdL„ZOdMdN„ZPdkdPdQ„ZQdRdS„ZRdTdU„ZSdV TdW¡ZUeUdXZVeUdYZWdZd[„ZXd\d]„ZYd^d_„ZZe [d`¡Z\e [da¡Z]dbdc„Z^ddde„Z_dfdg„Z`dS)lz” requests.utils ~~~~~~~~~~~~~~ This module provides utility functions that are used within Requests that are also useful for external consumption. éNé)Ú __version__)Úcerts)Úto_native_string)Úparse_http_list)ÚquoteÚurlparseÚbytesÚstrÚ OrderedDictÚunquoteÚ getproxiesÚ proxy_bypassÚ urlunparseÚ basestringÚ integer_typesÚis_py3Úproxy_bypass_environmentÚgetproxies_environmentÚMapping)Úcookiejar_from_dict)ÚCaseInsensitiveDict)Ú InvalidURLÚ InvalidHeaderÚFileModeWarningÚUnrewindableBodyError)z.netrcÚ_netrcéPi»)ÚhttpÚhttpsÚwin32cCsðytrddl}nddl}Wntk r.dSXy6| |jd¡}t| |d¡dƒ}| |d¡d}Wntk rzdSX|r„|sˆdS|  d¡}xX|D]P}|dkr°d|kr°d S|  dd ¡}|  d d ¡}|  d d¡}t   ||t j ¡r˜d Sq˜WdS)NrFz;Software\Microsoft\Windows\CurrentVersion\Internet SettingsZ ProxyEnableZ ProxyOverrideú;zÚ.Tz\.Ú*z.*ú?)rÚwinregÚ_winregÚ ImportErrorÚOpenKeyÚHKEY_CURRENT_USERÚintÚ QueryValueExÚOSErrorÚsplitÚreplaceÚreÚmatchÚI)Úhostr%ZinternetSettingsZ proxyEnableZ proxyOverrideÚtest©r4úh/private/var/folders/_z/lgy7p8v17sqbdp14fgmxdlrsbydzry/T/pip-install-3xgtll61/requests/requests/utils.pyÚproxy_bypass_registry/s8        r6cCstƒrt|ƒSt|ƒSdS)zšReturn True, if the host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. N)rrr6)r2r4r4r5rVsrcCst|dƒr| ¡}|S)z/Returns an internal sequence dictionary update.Úitems)Úhasattrr7)Údr4r4r5Údict_to_sequencebs r:c Cs4d}d}t|dƒrt|ƒ}nbt|dƒr.|j}nPt|dƒr~y | ¡}Wntjk rZYn$Xt |¡j}d|jkr~t   dt ¡t|dƒ�ry |  ¡}Wn$t tfk rº|dk r¶|}Yn^Xt|dƒ�r|dk�ry&| dd ¡|  ¡}| |pòd¡Wnt tfk �rd}YnX|dk�r&d}td||ƒS) NrÚ__len__ÚlenÚfilenoÚba%Requests has determined the content-length for this request using the binary size of the file: however, the file has been opened in text mode (i.e. without the 'b' flag in the mode). This may lead to an incorrect content-length. In Requests 3.0, support will be removed for files in text mode.ÚtellÚseeké)r8r<r=ÚioÚUnsupportedOperationÚosÚfstatÚst_sizeÚmodeÚwarningsÚwarnrr?r,ÚIOErrorr@Úmax)ÚoÚ total_lengthÚcurrent_positionr=r4r4r5Ú super_lenks@             rOFc Csyöddlm}m}d}xJtD]B}ytj d |¡¡}Wntk rJdSXtj |¡r|}PqW|dkrndSt |ƒ}d}t |t ƒrŽ|  d¡}|j  |¡d} y6||ƒ | ¡} | rÒ| dr¾dnd} | | | dfSWn|tfk rò|rî‚YnXWnttfk �rYnXdS) z;Returns the Requests tuple auth for a given url from netrc.r)ÚnetrcÚNetrcParseErrorNz~/{}ó:ÚasciirrA)rPrQÚ NETRC_FILESrDÚpathÚ expanduserÚformatÚKeyErrorÚexistsrÚ isinstancer ÚdecodeÚnetlocr-ÚauthenticatorsrJr'ÚAttributeError) ÚurlÚ raise_errorsrPrQÚ netrc_pathÚfÚlocÚriÚsplitstrr2rÚlogin_ir4r4r5Úget_netrc_auth¨s8     rgcCsBt|ddƒ}|r>t|tƒr>|ddkr>|ddkr>tj |¡SdS)z0Tries to guess the filename of the given object.ÚnameNrú<éÿÿÿÿú>)ÚgetattrrZrrDrUÚbasename)Úobjrhr4r4r5Úguess_filenameÛs  rocCsºtj |¡r|Stj |¡\}}x2|rRtj |¡sRtj |¡\}}d ||g¡}q"Wt |¡sb|St |¡}|| ¡kr||St   ¡}tjj|f| d¡žŽ}tj |¡s¶|j ||d�}|S)zÄReplace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. ú/)rU) rDrUrYr-ÚjoinÚzipfileÚ is_zipfileÚZipFileÚnamelistÚtempfileÚ gettempdirÚextract)rUÚarchiveÚmemberÚprefixÚzip_fileÚtmpÚextracted_pathr4r4r5Úextract_zipped_pathsãs      rcCs.|dkr dSt|ttttfƒr&tdƒ‚t|ƒS)aÐTake an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict Nz+cannot encode objects that are not 2-tuples)rZr r Úboolr*Ú ValueErrorr )Úvaluer4r4r5Úfrom_key_val_lists rƒcCs@|dkr dSt|ttttfƒr&tdƒ‚t|tƒr8| ¡}t|ƒS)aŒTake an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples. :rtype: list Nz+cannot encode objects that are not 2-tuples) rZr r r€r*r�rr7Úlist)r‚r4r4r5Úto_key_val_lists r…cCs\g}xRt|ƒD]F}|dd…|dd…kr6dkrJnnt|dd…ƒ}| |¡qW|S)aParse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list Nrrjú")Ú_parse_list_headerÚunquote_header_valueÚappend)r‚ÚresultÚitemr4r4r5Úparse_list_header8s (rŒcCs|i}xrt|ƒD]f}d|kr$d||<q| dd¡\}}|dd…|dd…krXdkrlnnt|dd…ƒ}|||<qW|S)a^Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict ú=Nrrjr†)r‡r-rˆ)r‚rŠr‹rhr4r4r5Úparse_dict_headerXs( rŽcCs\|rX|d|dkr dkrXnn4|dd…}|rD|dd…dkrX| dd¡ d d¡S|S) zçUnquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str rrjr†rNrAz\\ú\z\")r.)r‚Ú is_filenamer4r4r5rˆ{s $ rˆcCs"i}x|D]}|j||j<q W|S)z€Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict )r‚rh)ÚcjÚ cookie_dictÚcookier4r4r5Údict_from_cookiejar”s r”cCs t||ƒS)zÂReturns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar )r)r‘r’r4r4r5Úadd_dict_to_cookiejar£sr•cCsTt dt¡tjdtjd�}tjdtjd�}t d¡}| |¡| |¡| |¡S)zlReturns encodings from given content string. :param content: bytestring to extract encodings from. z¤In requests 3.0, get_encodings_from_content will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)z!])Úflagsz+]z$^<\?xml.*?encoding=["\']*(.+?)["\'>])rHrIÚDeprecationWarningr/Úcompiler1Úfindall)ÚcontentÚ charset_reÚ pragma_reÚxml_rer4r4r5Úget_encodings_from_content®s ržc Csž| d¡}|d ¡|dd…}}i}d}xh|D]`}| ¡}|r2|d}}| d¡} | dkr†|d| … |¡}|| dd… |¡}||| ¡<q2W||fS) z¦Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters r!rrNz"' Tr�rj)r-ÚstripÚfindÚlower) ÚheaderÚtokensÚ content_typeÚparamsÚ params_dictÚitems_to_stripÚparamÚkeyr‚Úindex_of_equalsr4r4r5Ú_parse_content_type_headerÂs    r«cCsD| d¡}|sdSt|ƒ\}}d|kr4|d d¡Sd|kr@dSdS)z}Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str z content-typeNÚcharsetz'"Útextz ISO-8859-1)Úgetr«rŸ)Úheadersr¤r¥r4r4r5Úget_encoding_from_headersÛs  r°ccsr|jdkr"x|D] }|VqWdSt |j¡dd�}x |D]}| |¡}|r:|Vq:W|jddd�}|rn|VdS)zStream decodes a iterator.Nr.)ÚerrorsóT)Úfinal)ÚencodingÚcodecsÚgetincrementaldecoderr[)ÚiteratorÚrr‹ÚdecoderÚchunkÚrvr4r4r5Ústream_decode_response_unicodeðs      r¼ccsLd}|dks|dkrt|ƒ}x*|t|ƒkrF||||…V||7}qWdS)z Iterate over slices of a string.rN)r<)ÚstringÚ slice_lengthÚposr4r4r5Ú iter_slicess rÀcCsvt dt¡g}t|jƒ}|rJy t|j|ƒStk rH| |¡YnXyt|j|dd�St k rp|jSXdS)zâReturns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str z£In requests 3.0, get_unicode_from_response will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)r.)r±N) rHrIr—r°r¯r ršÚ UnicodeErrorr‰Ú TypeError)r¸Útried_encodingsr´r4r4r5Úget_unicode_from_response s   rÄzBABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~c CsÈ| d¡}x²tdt|ƒƒD] }||dd…}t|ƒdkrª| ¡rªytt|dƒƒ}Wn tk rttd|ƒ‚YnX|tkr˜|||dd…||<qºd||||<qd||||<qWd  |¡S) z¨Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str ú%rrrAéz%Invalid percent-escape sequence: '%s'NÚ) r-Úranger<ÚisalnumÚchrr*r�rÚUNRESERVED_SETrq)ÚuriÚpartsÚiÚhÚcr4r4r5Úunquote_unreserved5s rÑcCs:d}d}ytt|ƒ|d�Stk r4t||d�SXdS)z¬Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str z!#$%&'()*+,/:;=?@[]~z!#$&'()*+,/:;=?@[]~)ÚsafeN)rrÑr)rÌÚsafe_with_percentÚsafe_without_percentr4r4r5Ú requote_uriMs rÕcCslt dt |¡¡d}| d¡\}}t dt tt|ƒƒ¡¡d}t dt |¡¡d|@}||@||@kS)zïThis function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool z=Lrrp)ÚstructÚunpackÚsocketÚ inet_atonr-Údotted_netmaskr*)ÚipÚnetÚipaddrÚnetaddrÚbitsÚnetmaskÚnetworkr4r4r5Úaddress_in_networkcs râcCs&ddd|>dA}t t d|¡¡S)z�Converts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str lÿÿré z>I)rØÚ inet_ntoarÖÚpack)Úmaskrßr4r4r5rÚrsrÚcCs*yt |¡Wntjk r$dSXdS)z :rtype: bool FT)rØrÙÚerror)Ú string_ipr4r4r5Úis_ipv4_address}s récCsˆ| d¡dkr€yt| d¡dƒ}Wntk r8dSX|dksJ|dkrNdSyt | d¡d¡Wq„tjk r|dSXndSdS)zV Very simple check of the cidr format in no_proxy variable. :rtype: bool rprFrãrT)Úcountr*r-r�rØrÙrç)Ústring_networkrær4r4r5Ú is_valid_cidrˆsrìc csT|dk }|r"tj |¡}|tj|<z dVWd|rN|dkrDtj|=n |tj|<XdS)zÎSet the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothingN)rDÚenvironr®)Úenv_namer‚Ú value_changedÚ old_valuer4r4r5Ú set_environ s    rñc Cs,dd„}|}|dkr|dƒ}t|ƒ}|jdkr2dS|rØdd„| dd ¡ d ¡Dƒ}t|jƒr”xz|D],}t|ƒr€t|j|ƒrŽdSqb|j|krbdSqbWnD|j}|jr°|d  |j¡7}x&|D]}|j  |¡sÐ|  |¡r¶dSq¶Wt d|ƒ�6yt |jƒ}Wn t t jfk �rd }YnXWdQRX|�r(dSd S) zL Returns whether we should bypass proxies or not. :rtype: bool cSstj |¡ptj | ¡¡S)N)rDrír®Úupper)Úkr4r4r5Ú¾sz'should_bypass_proxies..NÚno_proxyTcss|]}|r|VqdS)Nr4)Ú.0r2r4r4r5ú Ïsz(should_bypass_proxies..ú rÇú,z:{}F)rÚhostnamer.r-rérìrâÚportrWÚendswithrñrrÂrØÚgaierror) r_rõÚ get_proxyÚ no_proxy_argÚparsedÚproxy_ipÚhost_with_portr2Úbypassr4r4r5Úshould_bypass_proxies¶s<        rcCst||d�riStƒSdS)zA Return a dict of environment proxies. :rtype: dict )rõN)rr )r_rõr4r4r5Úget_environ_proxiesós rcCsv|pi}t|ƒ}|jdkr.| |j| d¡¡S|jd|j|jd|jdg}d}x|D]}||krX||}PqXW|S)z­Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs NÚallz://zall://)rrúr®Úscheme)r_ÚproxiesÚurlpartsÚ proxy_keysÚproxyÚ proxy_keyr4r4r5Ú select_proxyÿs  r úpython-requestscCs d|tfS)zO Return a string representing the default user agent. :rtype: str z%s/%s)r)rhr4r4r5Údefault_user_agentsrcCsttƒd d¡dddœƒS)z9 :rtype: requests.structures.CaseInsensitiveDict z, )ÚgzipÚdeflatez*/*z keep-alive)z User-AgentzAccept-EncodingÚAcceptÚ Connection)rrrqr4r4r4r5Údefault_headers"s rc CsÒg}d}| |¡}|s|Sx²t d|¡D]¢}y| dd¡\}}Wntk r^|d}}YnXd| d¡i}xP| d¡D]B}y| d¡\}}Wntk r¦PYnX| |¡|| |¡<qzW| |¡q(W|S) z¼Return a list of parsed link headers proxies. i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" :rtype: list z '"z, * '"r�)rŸr/r-r�r‰) r‚ÚlinksÚ replace_charsÚvalr_r¥Úlinkr¨r©r4r4r5Úparse_header_links.s& rúrSrAécCsÐ|dd…}|tjtjfkr dS|dd…tjkr6dS|dd…tjtjfkrRdS| t¡}|dkrhd S|dkrœ|ddd…tkr†d S|d dd…tkrœd S|dkrÌ|dd…t kr¸d S|d d…t krÌdSdS)z :rtype: str Nézutf-32rz utf-8-sigrAzutf-16rzutf-8z utf-16-berz utf-16-lez utf-32-bez utf-32-le) rµÚ BOM_UTF32_LEÚ BOM_UTF32_BEÚBOM_UTF8Ú BOM_UTF16_LEÚ BOM_UTF16_BErêÚ_nullÚ_null2Ú_null3)ÚdataÚsampleÚ nullcountr4r4r5Úguess_json_utfYs*  r(cCs8t||ƒ\}}}}}}|s$||}}t||||||fƒS)zªGiven a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str )rr)r_Ú new_schemerr\rUr¥ÚqueryÚfragmentr4r4r5Úprepend_scheme_if_neededys r,c CsBt|ƒ}yt|jƒt|jƒf}Wnttfk r<d}YnX|S)z{Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) )rÇrÇ)rr ÚusernameÚpasswordr^rÂ)r_rÚauthr4r4r5Úget_auth_from_urlŠs  r0s^\S[^\r\n]*$|^$z^\S[^\r\n]*$|^$c Csf|\}}t|tƒrt}nt}y| |¡s4td|ƒ‚Wn*tk r`td||t|ƒfƒ‚YnXdS)zÕVerifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). z7Invalid return character or leading space in header: %sz>Value for header {%s: %s} must be of type str or bytes, not %sN)rZr Ú_CLEAN_HEADER_REGEX_BYTEÚ_CLEAN_HEADER_REGEX_STRr0rrÂÚtype)r¢rhr‚Úpatr4r4r5Úcheck_header_validityŸs  r5cCsFt|ƒ\}}}}}}|s"||}}| dd¡d}t|||||dfƒS)zW Given a url remove the fragment and the authentication part. :rtype: str ú@rrjrÇ)rÚrsplitr)r_rr\rUr¥r*r+r4r4r5Ú urldefragauth´s  r8c Cs`t|jddƒ}|dk rTt|jtƒrTy||jƒWq\ttfk rPtdƒ‚Yq\Xntdƒ‚dS)zfMove file pointer back to its recorded starting position so it can be read again on redirect. r@Nz;An error occurred when rewinding request body for redirect.z+Unable to rewind request body for redirect.)rlÚbodyrZÚ_body_positionrrJr,r)Úprepared_requestÚ body_seekr4r4r5Ú rewind_bodyÅsr=)F)F)N)r)aÚ__doc__rµÚ contextlibrBrDr/rØrÖÚsysrvrHrrrrÇrÚ_internal_utilsrÚcompatrr‡rrr r r r r rrrrrrrrÚcookiesrÚ structuresrÚ exceptionsrrrrrTÚwhereÚDEFAULT_CA_BUNDLE_PATHÚ DEFAULT_PORTSÚplatformr6r:rOrgrorrƒr…rŒrŽrˆr”r•ržr«r°r¼rÀrÄÚ frozensetrËrÑrÕrârÚrérìÚcontextmanagerrñrrr rrrÚencoder"r#r$r(r,r0r˜r1r2r5r8r=r4r4r4r5Ú sŠ    D    '  = 3  #   %  =   &