o {nh@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZmZddlmZddlmZddlmZmZmZmZdd lmZmZmZmZmZmZm Z dd lm!Z"dd lm#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)dd l*m+Z+dd l,m-Z-m.Z.m/Z/m0Z0ddl1m2Z2dZ3e4Z5dddZ6d7e8dedddZ9ej:dkrddZ;ddZ#ddZd$d%Z?d&d'Z@ejAd(d)ZBd*d+ZCd,d-ZDd.d/ZEd0d1ZFdtd2d3ZGd4d5ZHd6d7ZId8d9ZJd:d;ZKdd?ZMd@dAZNdBdCZOePdDZQdEdFZRdGdHZSdIdJZTdKdLZUdMdNZVdOdPZWejAdQdRZXdSdTZYdudUdVZZdWdXZ[dvdYdZZ\dwd\d]Z]d^d_Z^d`daZ_db`dcZaeaddZbeadeZcdfdgZddhdiZedjdkZfdldmZgdndoZhdpdqZidrdsZjdS)xz requests.utils ~~~~~~~~~~~~~~ This module provides utility functions that are used within Requests that are also useful for external consumption. N) OrderedDict) make_headers parse_url)certs __version__)_HEADER_VALIDATORS_BYTE_HEADER_VALIDATORS_STRHEADER_VALIDATORSto_native_string)Mapping basestringbytes getproxiesgetproxies_environment integer_types is_urllib3_1)parse_http_list) proxy_bypassproxy_bypass_environmentquotestrunquoteurlparse urlunparsecookiejar_from_dict)FileModeWarning InvalidHeader InvalidURLUnrewindableBodyError)CaseInsensitiveDict)z.netrc_netrcPi)httphttpsz, z,\s*T)accept_encodingzaccept-encodingwin32c Cszddl}Wn tyYdSwz||jd}t||dd}||dd}Wn ttfy8YdSw|r=|s?dS|d}t d|}|D]*}|dkrXd|vrXd S| dd }| d d }| d d}t ||t j rud SqKdS)NrFz;Software\Microsoft\Windows\CurrentVersion\Internet Settings ProxyEnable ProxyOverride;z.Tz\.*z.*?)winreg ImportErrorOpenKeyHKEY_CURRENT_USERint QueryValueExOSError ValueErrorsplitfilterreplacerematchI)hostr/internetSettings proxyEnable proxyOverridetestrB9/usr/local/lib/python3.10/dist-packages/requests/utils.pyproxy_bypass_registryMs<       rDcCstrt|St|S)zReturn True, if the host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. )rrrD)r=rBrBrCrssrcCst|dr |}|S)z/Returns an internal sequence dictionary update.items)hasattrrE)drBrBrCdict_to_sequences rHc Cs8d}d}tst|tr|d}t|drt|}n2t|dr#|j}n)t|drLz|}Wn tjt fy:Ynwt |j }d|j vrLtdtt|drz|}Wntyf|durd|}Yn)wt|d r|durz|dd |}||pdWn tyd}Ynw|durd}td||S) Nrutf-8__len__lenfilenoba%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.tellseek)r isinstancerencoderFrKrLioUnsupportedOperationAttributeErrorosfstatst_sizemodewarningswarnrrNr5rOmax)o total_lengthcurrent_positionrLrBrBrC super_lensN             r`Fc Cstjd}|dur|f}nddtD}z]ddlm}m}d}|D]}tj|}tj|r4|}nq"|dursz!get_netrc_auth..r)NetrcParseErrornetrcrrP)rVenvironget NETRC_FILESrfrepath expanduserexistsrhostnameauthenticatorsr5r0rU) url raise_errors netrc_filenetrc_locationsrerf netrc_pathrclocrir=r#login_irBrBrCget_netrc_auths>   rwcCsNt|dd}|rt|tr!|ddkr#|ddkr%tj|SdSdSdSdS)z0Tries to guess the filename of the given object.nameNr<>)getattrrQrrVrjbasename)objrxrBrBrCguess_filenames & rcCstj|r|Stj|\}}|r2tj|s2tj|\}}|s#nd||g}|r2tj|rt|s9|St|}||vrF|St }tj||dd}tj|syt |}| | |Wd|S1stwY|S)zReplace 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. /rzN)rVrjrlr7joinzipfile is_zipfileZipFilenamelisttempfile gettempdir atomic_openwriteread)rjarchivememberprefixzip_filetmpextracted_path file_handlerrBrBrCextract_zipped_pathss.       rccsztjtj|d\}}z"t|d }|VWdn1s"wYt||WdSty<t|w)z-Write a file to the disk in an atomic fashion)dirwbN) rmkstemprVrjdirnamefdopenr9 BaseExceptionremove)filenametmp_descriptortmp_name tmp_handlerrBrBrCr's  rcCs.|durdSt|ttttfrtdt|S)aTake 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') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict N+cannot encode objects that are not 2-tuples)rQrrboolr3r6rvaluerBrBrCfrom_key_val_list4s rcCs@|durdSt|ttttfrtdt|tr|}t|S)aTake 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') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list Nr) rQrrrr3r6r rElistrrBrBrCto_key_val_listOs rcCsXg}t|D]#}|dd|ddkrdkr$nnt|dd}||q|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 Nrrz")_parse_list_headerunquote_header_valueappend)rresultitemrBrBrCparse_list_headerms  ( rcCsxi}t|D]3}d|vrd||<q|dd\}}|dd|ddkr+dkr5nnt|dd}|||<q|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 =Nrrzr)rr7r)rrrrxrBrBrCparse_dict_headers ( rcCs^|r-|d|dkrdkr-n|S|dd}|r#|dddkr-|ddd dS|S) zUnquotes 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 rrzrrNrPz\\\z\")r9)r is_filenamerBrBrCrs " rcCsdd|D}|S)zReturns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict cSsi|]}|j|jqSrB)rxr)rbcookierBrBrC sz'dict_from_cookiejar..rBcj cookie_dictrBrBrCdict_from_cookiejarsrcCs t||S)zReturns 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 rrrBrBrCadd_dict_to_cookiejars rcCsTtdttjdtjd}tjdtjd}td}||||||S)zlReturns encodings from given content string. :param content: bytestring to extract encodings from. zIn 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=["\']*(.+?)["\'>])rZr[DeprecationWarningr:compiler<findall)content charset_re pragma_rexml_rerBrBrCget_encodings_from_contents  rc Cs|d}|d|dd}}i}d}|D]0}|}|rH|d}}|d} | dkrB|d| |}|| dd|}|||<q||fS) zReturns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters r+rrNz"' Trrz)r7stripfindlower) headertokens content_typeparams params_dictitems_to_stripparamkeyrindex_of_equalsrBrBrC_parse_content_type_headers    rcCsP|d}|s dSt|\}}d|vr|ddSd|vr dSd|vr&dSdS) z}Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str z content-typeNcharsetz'"textz ISO-8859-1zapplication/jsonrI)rhrr)headersrrrBrBrCget_encoding_from_headerss  rccsj|jdur |EdHdSt|jdd}|D] }||}|r$|Vq|jddd}|r3|VdSdS)zStream decodes an iterator.Nr9errorsT)final)encodingcodecsgetincrementaldecoderdecode)iteratorrdecoderchunkrvrBrBrCstream_decode_response_unicode*s    rccsXd}|dus |dkrt|}|t|kr*||||V||7}|t|ksdSdS)z Iterate over slices of a string.rN)rK)string slice_lengthposrBrBrC iter_slices;s rcCsvtdtg}t|j}|r%zt|j|WSty$||Ynwz t|j|ddWSt y:|jYSw)zReturns 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 zIn 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.)r9r) rZr[rrrrr UnicodeErrorr TypeError)rtried_encodingsrrBrBrCget_unicode_from_responseEs"     rzBABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~c Cs|d}tdt|D]Q}||dd}t|dkrT|rTz tt|d}Wnty8td|dw|tvrJ|||dd||<q d||||<q d||||<q d |S) zUn-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str %rrrPz"Invalid percent-escape sequence: ''N) r7rangerKisalnumchrr3r6r UNRESERVED_SETr)uripartsihcrBrBrCunquote_unreservedrs   rcCs:d}d}z tt||dWStyt||dYSw)zRe-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!#$&'()*+,/:;=?@[]~)safe)rrr )rsafe_with_percentsafe_without_percentrBrBrC requote_uris rcCsltdt|d}|d\}}tdttt|d}tdt|d|@}||@||@kS)zThis 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=Lrr)structunpacksocket inet_atonr7dotted_netmaskr3)ipnetipaddrnetaddrbitsnetmasknetworkrBrBrCaddress_in_networks rcCs&ddd|>dA}ttd|S)zConverts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str lr z>I)r inet_ntoarpack)maskrrBrBrCrsrcCs&zt|WdStyYdSw)z :rtype: bool FT)rrr5) string_iprBrBrCis_ipv4_addresss   r cCs|ddkr?z t|dd}Wn tyYdSw|dks%|dkr'dSz t|ddWdSty>YdSwdS)zV Very simple check of the cidr format in no_proxy variable. :rtype: bool rrFrrT)countr3r7r6rrr5)string_networkr rBrBrC is_valid_cidrs  rc csz|du}|rtj|}|tj|<zdVW|r*|dur#tj|=dS|tj|<dSdS|r<|dur7tj|=w|tj|<w)zSet 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)rVrgrh)env_namer value_changed old_valuerBrBrC set_environs   rc Cs8dd}|}|dur|d}t|}|jdurdS|rkdd|dd d D}t|jrJ|D]}t|r@t|j|r?dSq0|j|krHdSq0n!|j}|jrX|d |j7}|D]}|j|sg||rjdSqZt d|zt |j}Wnt t j fyd }YnwWdn1swY|rdSd S) zL Returns whether we should bypass proxies or not. :rtype: bool cSstj|p tj|SN)rVrgrhupper)rrBrBrC get_proxysz(should_bypass_proxies..get_proxyNno_proxyTcss|]}|r|VqdSrrB)rbr=rBrBrCrd sz(should_bypass_proxies.. r,:F)rrmr9r7r rrportendswithrrrrgaierror) rorr no_proxy_argparsedproxy_iphost_with_portr=bypassrBrBrCshould_bypass_proxiessJ       r"cCst||driStS)zA Return a dict of environment proxies. :rtype: dict r)r"r)rorrBrBrCget_environ_proxies0s r$cCsv|pi}t|}|jdur||j|dS|jd|j|jd|jdg}d}|D] }||vr8||}|Sq+|S)zSelect 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 Nallz://zall://)rrmrhscheme)roproxiesurlparts proxy_keysproxy proxy_keyrBrBrC select_proxy<s" r,c Cst|dur|ni}|j}t|j}|d}|}|r8t||ds8t||d}|||d}|r8||||S)aThis method takes proxy information from a request and configuration input to resolve a mapping of target proxies. This will consider settings such as NO_PROXY to strip proxy configurations. :param request: Request or PreparedRequest :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs :param trust_env: Boolean declaring whether to trust environment configs :rtype: dict Nrr#r%)rorr&rhcopyr"r$ setdefault) requestr' trust_envror&r new_proxiesenviron_proxiesr*rBrBrCresolve_proxiesVs     r3python-requestscCs|dtS)zO Return a string representing the default user agent. :rtype: str rr)rxrBrBrCdefault_user_agentqsr5cCstttdddS)z9 :rtype: requests.structures.CaseInsensitiveDict z*/*z keep-alive)z User-AgentzAccept-EncodingAccept Connection)r"r5DEFAULT_ACCEPT_ENCODINGrBrBrBrCdefault_headerszsr9c Csg}d}||}|s |Std|D]M}z |dd\}}Wnty-|d}}Ynwd|di}|dD] }z |d\}}Wn tyOYn w|||||<q:||q|S) zReturn 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)rr:r7r6r) rlinks replace_charsvalrorlinkrrrBrBrCparse_header_linkss*    r>asciirPcCs|dd}|tjtjfvrdS|ddtjkrdS|ddtjtjfvr)dS|t}|dkr4d S|dkrN|dddtkrCd S|d ddtkrNd S|dkrf|ddt kr\d S|d dt krfdSdS)z :rtype: str Nzutf-32rAz utf-8-sigrPzutf-16rrIz utf-16-berz utf-16-lez utf-32-bez utf-32-le) r BOM_UTF32_LE BOM_UTF32_BEBOM_UTF8 BOM_UTF16_LE BOM_UTF16_BEr _null_null2_null3)datasample nullcountrBrBrCguess_json_utfs*  rNc Cslt|}|\}}}}}}} |j} | s|| } }|r d|| g} |dur&|}|dur,d}t|| |d|| fS)zGiven 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 @Nr)rnetlocrr) ro new_schemerr&authr=rrjqueryfragmentrPrBrBrCprepend_scheme_if_neededs rUc Cs@t|}z t|jt|jf}W|Sttfyd}Y|Sw)z{Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) )rr)rrusernamepasswordrUr)rorrRrBrBrCget_auth_from_urlsrXcCs$|\}}t||dt||ddS)zVerifies that header parts don't contain leading whitespace reserved characters, or return characters. :param header: tuple, in the format (name, value). rrN)_validate_header_part)rrxrrBrBrCcheck_header_validitys rZcCsxt|tr t|}nt|trt|}ntd|d|dt|||s:|dkr.dnd}td|d|dS) Nz Header part (z) from z# must be of type str or bytes, not rrxrzTInvalid leading whitespace, reserved character(s), or return character(s) in header z: )rQrr rr rtyper;)r header_partheader_validator_index validator header_kindrBrBrCrY s&     rYcCsFt|\}}}}}}|s||}}|ddd}t|||||dfS)zW Given a url remove the fragment and the authentication part. :rtype: str rOrrzr)rrsplitr)ror&rPrjrrSrTrBrBrC urldefragauths  racCsRt|jdd}|dur%t|jtr%z||jWdSty$tdwtd)zfMove file pointer back to its recorded starting position so it can be read again on redirect. rONz;An error occurred when rewinding request body for redirect.z+Unable to rewind request body for redirect.)r|bodyrQ_body_positionrr5r!)prepared_request body_seekrBrBrC rewind_body/s  rf)Fr)T)r4)k__doc__r contextlibrSrVr:rrsysrrZr collectionsr urllib3.utilrrrrr_internal_utilsr r r r compatr rrrrrrrrrrrrrrrcookiesr exceptionsrrr r! structuresr"riwhereDEFAULT_CA_BUNDLE_PATH DEFAULT_PORTSrr7r8platformrDrHr`rwrrcontextmanagerrrrrrrrrrrrrrr frozensetrrrrrr rrr"r$r,r3r5r9r>rRrHrIrJrNrUrXrZrYrarfrBrBrBrCs   $ $    &  G,%   #   (    =    &