"""Parse (absolute and relative) URLs.urlparse module is based upon the following RFC specifications.RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fieldingand L. Masinter, January 2005.RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenterand L.Masinter, December 1999.RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T.Berners-Lee, R. Fielding, and L. Masinter, August 1998.RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June1995.RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.McCahill, December 1994RFC 3986 is considered the current standard and any future changes tourlparse module should conform with it. The urlparse module iscurrently not entirely compliant with this RFC due to defactoscenarios for parsing, and for backward compatibility purposes, someparsing quirks from older RFCs are retained. The testcases intest_urlparse.py provides a good indicator of parsing behavior.The WHATWG URL Parser spec should also be considered. We are not compliant withit either due to existing user code API behavior expectations (Hyrum's Law).It serves as a useful guide when making changes."""fromcollectionsimportnamedtupleimportfunctoolsimportmathimportreimporttypesimportwarningsimportipaddress__all__=["urlparse","urlunparse","urljoin","urldefrag","urlsplit","urlunsplit","urlencode","parse_qs","parse_qsl","quote","quote_plus","quote_from_bytes","unquote","unquote_plus","unquote_to_bytes","DefragResult","ParseResult","SplitResult","DefragResultBytes","ParseResultBytes","SplitResultBytes"]# A classification of schemes.# The empty string classifies URLs with no scheme specified,# being the default value returned by “urlsplit” and “urlparse”.uses_relative=['','ftp','http','gopher','nntp','imap','wais','file','https','shttp','mms','prospero','rtsp','rtsps','rtspu','sftp','svn','svn+ssh','ws','wss']uses_netloc=['','ftp','http','gopher','nntp','telnet','imap','wais','file','mms','https','shttp','snews','prospero','rtsp','rtsps','rtspu','rsync','svn','svn+ssh','sftp','nfs','git','git+ssh','ws','wss','itms-services']uses_params=['','ftp','hdl','prospero','http','imap','https','shttp','rtsp','rtsps','rtspu','sip','sips','mms','sftp','tel']# These are not actually used anymore, but should stay for backwards# compatibility. (They are undocumented, but have a public-looking name.)non_hierarchical=['gopher','hdl','mailto','news','telnet','wais','imap','snews','sip','sips']uses_query=['','http','wais','imap','https','shttp','mms','gopher','rtsp','rtsps','rtspu','sip','sips']uses_fragment=['','ftp','hdl','http','gopher','news','nntp','wais','https','shttp','snews','file','prospero']# Characters valid in scheme namesscheme_chars=('abcdefghijklmnopqrstuvwxyz''ABCDEFGHIJKLMNOPQRSTUVWXYZ''0123456789''+-.')# Leading and trailing C0 control and space to be stripped per WHATWG spec.# == "".join([chr(i) for i in range(0, 0x20 + 1)])_WHATWG_C0_CONTROL_OR_SPACE='\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f '# Unsafe bytes to be removed per WHATWG spec_UNSAFE_URL_BYTES_TO_REMOVE=['\t','\r','\n']defclear_cache():"""Clear internal performance caches. Undocumented; some tests want it."""urlsplit.cache_clear()_byte_quoter_factory.cache_clear()# Helpers for bytes handling# For 3.2, we deliberately require applications that# handle improperly quoted URLs to do their own# decoding and encoding. If valid use cases are# presented, we may relax this by using latin-1# decoding internally for 3.3_implicit_encoding='ascii'_implicit_errors='strict'def_noop(obj):returnobjdef_encode_result(obj,encoding=_implicit_encoding,errors=_implicit_errors):returnobj.encode(encoding,errors)def_decode_args(args,encoding=_implicit_encoding,errors=_implicit_errors):returntuple(x.decode(encoding,errors)ifxelse''forxinargs)def_coerce_args(*args):# Invokes decode if necessary to create str args# and returns the coerced inputs along with# an appropriate result coercion function# - noop for str inputs# - encoding function otherwisestr_input=isinstance(args[0],str)forarginargs[1:]:# We special-case the empty string to support the# "scheme=''" default argument to some functionsifargandisinstance(arg,str)!=str_input:raiseTypeError("Cannot mix str and non-str arguments")ifstr_input:returnargs+(_noop,)return_decode_args(args)+(_encode_result,)# Result objects are more helpful than simple tuplesclass_ResultMixinStr(object):"""Standard approach to encoding parsed results from str to bytes"""__slots__=()defencode(self,encoding='ascii',errors='strict'):returnself._encoded_counterpart(*(x.encode(encoding,errors)forxinself))class_ResultMixinBytes(object):"""Standard approach to decoding parsed results from bytes to str"""__slots__=()defdecode(self,encoding='ascii',errors='strict'):returnself._decoded_counterpart(*(x.decode(encoding,errors)forxinself))class_NetlocResultMixinBase(object):"""Shared methods for the parsed result objects containing a netloc element"""__slots__=()@propertydefusername(self):returnself._userinfo[0]@propertydefpassword(self):returnself._userinfo[1]@propertydefhostname(self):hostname=self._hostinfo[0]ifnothostname:returnNone# Scoped IPv6 address may have zone info, which must not be lowercased# like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keysseparator='%'ifisinstance(hostname,str)elseb'%'hostname,percent,zone=hostname.partition(separator)returnhostname.lower()+percent+zone@propertydefport(self):port=self._hostinfo[1]ifportisnotNone:ifport.isdigit()andport.isascii():port=int(port)else:raiseValueError(f"Port could not be cast to integer value as {port!r}")ifnot(0<=port<=65535):raiseValueError("Port out of range 0-65535")returnport__class_getitem__=classmethod(types.GenericAlias)class_NetlocResultMixinStr(_NetlocResultMixinBase,_ResultMixinStr):__slots__=()@propertydef_userinfo(self):netloc=self.netlocuserinfo,have_info,hostinfo=netloc.rpartition('@')ifhave_info:username,have_password,password=userinfo.partition(':')ifnothave_password:password=Noneelse:username=password=Nonereturnusername,password@propertydef_hostinfo(self):netloc=self.netloc_,_,hostinfo=netloc.rpartition('@')_,have_open_br,bracketed=hostinfo.partition('[')ifhave_open_br:hostname,_,port=bracketed.partition(']')_,_,port=port.partition(':')else:hostname,_,port=hostinfo.partition(':')ifnotport:port=Nonereturnhostname,portclass_NetlocResultMixinBytes(_NetlocResultMixinBase,_ResultMixinBytes):__slots__=()@propertydef_userinfo(self):netloc=self.netlocuserinfo,have_info,hostinfo=netloc.rpartition(b'@')ifhave_info:username,have_password,password=userinfo.partition(b':')ifnothave_password:password=Noneelse:username=password=Nonereturnusername,password@propertydef_hostinfo(self):netloc=self.netloc_,_,hostinfo=netloc.rpartition(b'@')_,have_open_br,bracketed=hostinfo.partition(b'[')ifhave_open_br:hostname,_,port=bracketed.partition(b']')_,_,port=port.partition(b':')else:hostname,_,port=hostinfo.partition(b':')ifnotport:port=Nonereturnhostname,port_DefragResultBase=namedtuple('DefragResult','url fragment')_SplitResultBase=namedtuple('SplitResult','scheme netloc path query fragment')_ParseResultBase=namedtuple('ParseResult','scheme netloc path params query fragment')_DefragResultBase.__doc__="""DefragResult(url, fragment)A 2-tuple that contains the url without fragment identifier and the fragmentidentifier as a separate argument."""_DefragResultBase.url.__doc__="""The URL with no fragment identifier."""_DefragResultBase.fragment.__doc__="""Fragment identifier separated from URL, that allows indirect identification of asecondary resource by reference to a primary resource and additional identifyinginformation."""_SplitResultBase.__doc__="""SplitResult(scheme, netloc, path, query, fragment)A 5-tuple that contains the different components of a URL. Similar toParseResult, but does not split params."""_SplitResultBase.scheme.__doc__="""Specifies URL scheme for the request."""_SplitResultBase.netloc.__doc__="""Network location where the request is made to."""_SplitResultBase.path.__doc__="""The hierarchical path, such as the path to a file to download."""_SplitResultBase.query.__doc__="""The query component, that contains non-hierarchical data, that along with datain path component, identifies a resource in the scope of URI's scheme andnetwork location."""_SplitResultBase.fragment.__doc__="""Fragment identifier, that allows indirect identification of a secondary resourceby reference to a primary resource and additional identifying information."""_ParseResultBase.__doc__="""ParseResult(scheme, netloc, path, params, query, fragment)A 6-tuple that contains components of a parsed URL."""_ParseResultBase.scheme.__doc__=_SplitResultBase.scheme.__doc___ParseResultBase.netloc.__doc__=_SplitResultBase.netloc.__doc___ParseResultBase.path.__doc__=_SplitResultBase.path.__doc___ParseResultBase.params.__doc__="""Parameters for last path element used to dereference the URI in order to provideaccess to perform some operation on the resource."""_ParseResultBase.query.__doc__=_SplitResultBase.query.__doc___ParseResultBase.fragment.__doc__=_SplitResultBase.fragment.__doc__# For backwards compatibility, alias _NetlocResultMixinStr# ResultBase is no longer part of the documented API, but it is# retained since deprecating it isn't worth the hassleResultBase=_NetlocResultMixinStr# Structured result objects for string data
# Set up the encode/decode result pairsdef_fix_result_transcoding():_result_pairs=((DefragResult,DefragResultBytes),(SplitResult,SplitResultBytes),(ParseResult,ParseResultBytes),)for_decoded,_encodedin_result_pairs:_decoded._encoded_counterpart=_encoded_encoded._decoded_counterpart=_decoded_fix_result_transcoding()del_fix_result_transcoding
[文档]defurlparse(url,scheme='',allow_fragments=True):"""Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> The result is a named 6-tuple with fields corresponding to the above. It is either a ParseResult or ParseResultBytes object, depending on the type of the url parameter. The username, password, hostname, and port sub-components of netloc can also be accessed as attributes of the returned object. The scheme argument provides the default value of the scheme component when no scheme is found in url. If allow_fragments is False, no attempt is made to separate the fragment component from the previous component, which can be either path or query. Note that % escapes are not expanded. """url,scheme,_coerce_result=_coerce_args(url,scheme)splitresult=urlsplit(url,scheme,allow_fragments)scheme,netloc,url,query,fragment=splitresultifschemeinuses_paramsand';'inurl:url,params=_splitparams(url)else:params=''result=ParseResult(scheme,netloc,url,params,query,fragment)return_coerce_result(result)
def_splitparams(url):if'/'inurl:i=url.find(';',url.rfind('/'))ifi<0:returnurl,''else:i=url.find(';')returnurl[:i],url[i+1:]def_splitnetloc(url,start=0):delim=len(url)# position of end of domain part of url, default is endforcin'/?#':# look for delimiters; the order is NOT importantwdelim=url.find(c,start)# find first of this delimifwdelim>=0:# if founddelim=min(delim,wdelim)# use earliest delim positionreturnurl[start:delim],url[delim:]# return (domain, rest)def_checknetloc(netloc):ifnotnetlocornetloc.isascii():return# looking for characters like \u2100 that expand to 'a/c'# IDNA uses NFKC equivalence, so normalize for this checkimportunicodedatan=netloc.replace('@','')# ignore characters already includedn=n.replace(':','')# but not the surrounding textn=n.replace('#','')n=n.replace('?','')netloc2=unicodedata.normalize('NFKC',n)ifn==netloc2:returnforcin'/?#@:':ifcinnetloc2:raiseValueError("netloc '"+netloc+"' contains invalid "+"characters under NFKC normalization")# Valid bracketed hosts are defined in# https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/def_check_bracketed_host(hostname):ifhostname.startswith('v'):ifnotre.match(r"\Av[a-fA-F0-9]+\..+\Z",hostname):raiseValueError(f"IPvFuture address is invalid")else:ip=ipaddress.ip_address(hostname)# Throws Value Error if not IPv6 or IPv4ifisinstance(ip,ipaddress.IPv4Address):raiseValueError(f"An IPv4 address cannot be in brackets")# typed=True avoids BytesWarnings being emitted during cache key# comparison since this API supports both bytes and str input.
[文档]@functools.lru_cache(typed=True)defurlsplit(url,scheme='',allow_fragments=True):"""Parse a URL into 5 components: <scheme>://<netloc>/<path>?<query>#<fragment> The result is a named 5-tuple with fields corresponding to the above. It is either a SplitResult or SplitResultBytes object, depending on the type of the url parameter. The username, password, hostname, and port sub-components of netloc can also be accessed as attributes of the returned object. The scheme argument provides the default value of the scheme component when no scheme is found in url. If allow_fragments is False, no attempt is made to separate the fragment component from the previous component, which can be either path or query. Note that % escapes are not expanded. """url,scheme,_coerce_result=_coerce_args(url,scheme)# Only lstrip url as some applications rely on preserving trailing space.# (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both)url=url.lstrip(_WHATWG_C0_CONTROL_OR_SPACE)scheme=scheme.strip(_WHATWG_C0_CONTROL_OR_SPACE)forbin_UNSAFE_URL_BYTES_TO_REMOVE:url=url.replace(b,"")scheme=scheme.replace(b,"")allow_fragments=bool(allow_fragments)netloc=query=fragment=''i=url.find(':')ifi>0andurl[0].isascii()andurl[0].isalpha():forcinurl[:i]:ifcnotinscheme_chars:breakelse:scheme,url=url[:i].lower(),url[i+1:]ifurl[:2]=='//':netloc,url=_splitnetloc(url,2)if(('['innetlocand']'notinnetloc)or(']'innetlocand'['notinnetloc)):raiseValueError("Invalid IPv6 URL")if'['innetlocand']'innetloc:bracketed_host=netloc.partition('[')[2].partition(']')[0]_check_bracketed_host(bracketed_host)ifallow_fragmentsand'#'inurl:url,fragment=url.split('#',1)if'?'inurl:url,query=url.split('?',1)_checknetloc(netloc)v=SplitResult(scheme,netloc,url,query,fragment)return_coerce_result(v)
[文档]defurlunparse(components):"""Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent)."""scheme,netloc,url,params,query,fragment,_coerce_result=(_coerce_args(*components))ifparams:url="%s;%s"%(url,params)return_coerce_result(urlunsplit((scheme,netloc,url,query,fragment)))
[文档]defurlunsplit(components):"""Combine the elements of a tuple as returned by urlsplit() into a complete URL as a string. The data argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent)."""scheme,netloc,url,query,fragment,_coerce_result=(_coerce_args(*components))ifnetloc:ifurlandurl[:1]!='/':url='/'+urlurl='//'+netloc+urlelifurl[:2]=='//':url='//'+urlelifschemeandschemeinuses_netlocand(noturlorurl[:1]=='/'):url='//'+urlifscheme:url=scheme+':'+urlifquery:url=url+'?'+queryiffragment:url=url+'#'+fragmentreturn_coerce_result(url)
[文档]defurljoin(base,url,allow_fragments=True):"""Join a base URL and a possibly relative URL to form an absolute interpretation of the latter."""ifnotbase:returnurlifnoturl:returnbasebase,url,_coerce_result=_coerce_args(base,url)bscheme,bnetloc,bpath,bparams,bquery,bfragment= \
urlparse(base,'',allow_fragments)scheme,netloc,path,params,query,fragment= \
urlparse(url,bscheme,allow_fragments)ifscheme!=bschemeorschemenotinuses_relative:return_coerce_result(url)ifschemeinuses_netloc:ifnetloc:return_coerce_result(urlunparse((scheme,netloc,path,params,query,fragment)))netloc=bnetlocifnotpathandnotparams:path=bpathparams=bparamsifnotquery:query=bqueryreturn_coerce_result(urlunparse((scheme,netloc,path,params,query,fragment)))base_parts=bpath.split('/')ifbase_parts[-1]!='':# the last item is not a directory, so will not be taken into account# in resolving the relative pathdelbase_parts[-1]# for rfc3986, ignore all base path should the first character be root.ifpath[:1]=='/':segments=path.split('/')else:segments=base_parts+path.split('/')# filter out elements that would cause redundant slashes on re-joining# the resolved_pathsegments[1:-1]=filter(None,segments[1:-1])resolved_path=[]forseginsegments:ifseg=='..':try:resolved_path.pop()exceptIndexError:# ignore any .. segments that would otherwise cause an IndexError# when popped from resolved_path if resolving for rfc3986passelifseg=='.':continueelse:resolved_path.append(seg)ifsegments[-1]in('.','..'):# do some post-processing here. if the last segment was a relative dir,# then we need to append the trailing '/'resolved_path.append('')return_coerce_result(urlunparse((scheme,netloc,'/'.join(resolved_path)or'/',params,query,fragment)))
[文档]defurldefrag(url):"""Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the empty string. """url,_coerce_result=_coerce_args(url)if'#'inurl:s,n,p,a,q,frag=urlparse(url)defrag=urlunparse((s,n,p,a,q,''))else:frag=''defrag=urlreturn_coerce_result(DefragResult(defrag,frag))
def_unquote_impl(string:bytes|bytearray|str)->bytes|bytearray:# Note: strings are encoded as UTF-8. This is only an issue if it contains# unescaped non-ASCII characters, which URIs should not.ifnotstring:# Is it a string-like object?string.splitreturnb''ifisinstance(string,str):string=string.encode('utf-8')bits=string.split(b'%')iflen(bits)==1:returnstringres=bytearray(bits[0])append=res.extend# Delay the initialization of the table to not waste memory# if the function is never calledglobal_hextobyteif_hextobyteisNone:_hextobyte={(a+b).encode():bytes.fromhex(a+b)forain_hexdigforbin_hexdig}foriteminbits[1:]:try:append(_hextobyte[item[:2]])append(item[2:])exceptKeyError:append(b'%')append(item)returnres_asciire=re.compile('([\x00-\x7f]+)')def_generate_unquoted_parts(string,encoding,errors):previous_match_end=0forascii_matchin_asciire.finditer(string):start,end=ascii_match.span()yieldstring[previous_match_end:start]# Non-ASCII# The ascii_match[1] group == string[start:end].yield_unquote_impl(ascii_match[1]).decode(encoding,errors)previous_match_end=endyieldstring[previous_match_end:]# Non-ASCII tail
[文档]defunquote(string,encoding='utf-8',errors='replace'):"""Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-encoded sequences are decoded with UTF-8, and invalid sequences are replaced by a placeholder character. unquote('abc%20def') -> 'abc def'. """ifisinstance(string,bytes):return_unquote_impl(string).decode(encoding,errors)if'%'notinstring:# Is it a string-like object?string.splitreturnstringifencodingisNone:encoding='utf-8'iferrorsisNone:errors='replace'return''.join(_generate_unquoted_parts(string,encoding,errors))
[文档]defparse_qs(qs,keep_blank_values=False,strict_parsing=False,encoding='utf-8',errors='replace',max_num_fields=None,separator='&'):"""Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. max_num_fields: int. If set, then throws a ValueError if there are more than n fields read by parse_qsl(). separator: str. The symbol to use for separating the query arguments. Defaults to &. Returns a dictionary. """parsed_result={}pairs=parse_qsl(qs,keep_blank_values,strict_parsing,encoding=encoding,errors=errors,max_num_fields=max_num_fields,separator=separator)forname,valueinpairs:ifnameinparsed_result:parsed_result[name].append(value)else:parsed_result[name]=[value]returnparsed_result
[文档]defparse_qsl(qs,keep_blank_values=False,strict_parsing=False,encoding='utf-8',errors='replace',max_num_fields=None,separator='&'):"""Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. max_num_fields: int. If set, then throws a ValueError if there are more than n fields read by parse_qsl(). separator: str. The symbol to use for separating the query arguments. Defaults to &. Returns a list, as G-d intended. """ifnotseparatorornotisinstance(separator,(str,bytes)):raiseValueError("Separator must be of type string or bytes.")ifisinstance(qs,str):ifnotisinstance(separator,str):separator=str(separator,'ascii')eq='='def_unquote(s):returnunquote_plus(s,encoding=encoding,errors=errors)else:ifnotqs:return[]# Use memoryview() to reject integers and iterables,# acceptable by the bytes constructor.qs=bytes(memoryview(qs))ifisinstance(separator,str):separator=bytes(separator,'ascii')eq=b'='def_unquote(s):returnunquote_to_bytes(s.replace(b'+',b' '))ifnotqs:return[]# If max_num_fields is defined then check that the number of fields# is less than max_num_fields. This prevents a memory exhaustion DOS# attack via post bodies with many fields.ifmax_num_fieldsisnotNone:num_fields=1+qs.count(separator)ifmax_num_fields<num_fields:raiseValueError('Max number of fields exceeded')r=[]forname_valueinqs.split(separator):ifname_valueorstrict_parsing:name,has_eq,value=name_value.partition(eq)ifnothas_eqandstrict_parsing:raiseValueError("bad query field: %r"%(name_value,))ifvalueorkeep_blank_values:name=_unquote(name)value=_unquote(value)r.append((name,value))returnr
[文档]defunquote_plus(string,encoding='utf-8',errors='replace'):"""Like unquote(), but also replace plus signs by spaces, as required for unquoting HTML form values. unquote_plus('%7e/abc+def') -> '~/abc def' """string=string.replace('+',' ')returnunquote(string,encoding,errors)
_ALWAYS_SAFE=frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'b'abcdefghijklmnopqrstuvwxyz'b'0123456789'b'_.-~')_ALWAYS_SAFE_BYTES=bytes(_ALWAYS_SAFE)def__getattr__(name):ifname=='Quoter':warnings.warn('Deprecated in 3.11. ''urllib.parse.Quoter will be removed in Python 3.14. ''It was not intended to be a public API.',DeprecationWarning,stacklevel=2)return_QuoterraiseAttributeError(f'module {__name__!r} has no attribute {name!r}')class_Quoter(dict):"""A mapping from bytes numbers (in range(0,256)) to strings. String values are percent-encoded byte values, unless the key < 128, and in either of the specified safe set, or the always safe set. """# Keeps a cache internally, via __missing__, for efficiency (lookups# of cached keys don't call Python code at all).def__init__(self,safe):"""safe: bytes object."""self.safe=_ALWAYS_SAFE.union(safe)def__repr__(self):returnf"<Quoter {dict(self)!r}>"def__missing__(self,b):# Handle a cache miss. Store quoted string in cache and return.res=chr(b)ifbinself.safeelse'%{:02X}'.format(b)self[b]=resreturnres
[文档]defquote(string,safe='/',encoding=None,errors=None):"""quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. The quote function offers a cautious (not minimal) way to quote a string for most of these parts. RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists the following (un)reserved characters. unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" reserved = gen-delims / sub-delims gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" Each of the reserved characters is reserved in some component of a URL, but not necessarily in all of them. The quote function %-escapes all characters that are neither in the unreserved chars ("always safe") nor the additional chars set via the safe arg. The default for the safe arg is '/'. The character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are to be preserved. Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings. Now, "~" is included in the set of unreserved characters. string and safe may be either str or bytes objects. encoding and errors must not be specified if string is a bytes object. The optional encoding and errors parameters specify how to deal with non-ASCII characters, as accepted by the str.encode method. By default, encoding='utf-8' (characters are encoded with UTF-8), and errors='strict' (unsupported characters raise a UnicodeEncodeError). """ifisinstance(string,str):ifnotstring:returnstringifencodingisNone:encoding='utf-8'iferrorsisNone:errors='strict'string=string.encode(encoding,errors)else:ifencodingisnotNone:raiseTypeError("quote() doesn't support 'encoding' for bytes")iferrorsisnotNone:raiseTypeError("quote() doesn't support 'errors' for bytes")returnquote_from_bytes(string,safe)
[文档]defquote_plus(string,safe='',encoding=None,errors=None):"""Like quote(), but also replace ' ' with '+', as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'. """# Check if ' ' in string, where string may either be a str or bytes. If# there are no spaces, the regular quote will produce the right answer.if((isinstance(string,str)and' 'notinstring)or(isinstance(string,bytes)andb' 'notinstring)):returnquote(string,safe,encoding,errors)ifisinstance(safe,str):space=' 'else:space=b' 'string=quote(string,safe+space,encoding,errors)returnstring.replace(' ','+')
# Expectation: A typical program is unlikely to create more than 5 of these.@functools.lru_cachedef_byte_quoter_factory(safe):return_Quoter(safe).__getitem__
[文档]defquote_from_bytes(bs,safe='/'):"""Like quote(), but accepts a bytes object rather than a str, and does not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f' """ifnotisinstance(bs,(bytes,bytearray)):raiseTypeError("quote_from_bytes() expected bytes")ifnotbs:return''ifisinstance(safe,str):# Normalize 'safe' by converting to bytes and removing non-ASCII charssafe=safe.encode('ascii','ignore')else:# List comprehensions are faster than generator expressions.safe=bytes([cforcinsafeifc<128])ifnotbs.rstrip(_ALWAYS_SAFE_BYTES+safe):returnbs.decode()quoter=_byte_quoter_factory(safe)if(bs_len:=len(bs))<200_000:return''.join(map(quoter,bs))else:# This saves memory - https://github.com/python/cpython/issues/95865chunk_size=math.isqrt(bs_len)chunks=[''.join(map(quoter,bs[i:i+chunk_size]))foriinrange(0,bs_len,chunk_size)]return''.join(chunks)
[文档]defurlencode(query,doseq=False,safe='',encoding=None,errors=None,quote_via=quote_plus):"""Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. The components of a query arg may each be either a string or a bytes type. The safe, encoding, and errors parameters are passed down to the function specified by quote_via (encoding and errors only if a component is a str). """ifhasattr(query,"items"):query=query.items()else:# It's a bother at times that strings and string-like objects are# sequences.try:# non-sequence items should not work with len()# non-empty strings will fail thisiflen(query)andnotisinstance(query[0],tuple):raiseTypeError# Zero-length sequences of all types will get here and succeed,# but that's a minor nit. Since the original implementation# allowed empty dicts that type of behavior probably should be# preserved for consistencyexceptTypeErroraserr:raiseTypeError("not a valid non-string sequence ""or mapping object")fromerrl=[]ifnotdoseq:fork,vinquery:ifisinstance(k,bytes):k=quote_via(k,safe)else:k=quote_via(str(k),safe,encoding,errors)ifisinstance(v,bytes):v=quote_via(v,safe)else:v=quote_via(str(v),safe,encoding,errors)l.append(k+'='+v)else:fork,vinquery:ifisinstance(k,bytes):k=quote_via(k,safe)else:k=quote_via(str(k),safe,encoding,errors)ifisinstance(v,bytes):v=quote_via(v,safe)l.append(k+'='+v)elifisinstance(v,str):v=quote_via(v,safe,encoding,errors)l.append(k+'='+v)else:try:# Is this a sufficient test for sequence-ness?x=len(v)exceptTypeError:# not a sequencev=quote_via(str(v),safe,encoding,errors)l.append(k+'='+v)else:# loop over the sequenceforeltinv:ifisinstance(elt,bytes):elt=quote_via(elt,safe)else:elt=quote_via(str(elt),safe,encoding,errors)l.append(k+'='+elt)return'&'.join(l)
defto_bytes(url):warnings.warn("urllib.parse.to_bytes() is deprecated as of 3.8",DeprecationWarning,stacklevel=2)return_to_bytes(url)def_to_bytes(url):"""to_bytes(u"URL") --> 'URL'."""# Most URL schemes require ASCII. If that changes, the conversion# can be relaxed.# XXX get rid of to_bytes()ifisinstance(url,str):try:url=url.encode("ASCII").decode()exceptUnicodeError:raiseUnicodeError("URL "+repr(url)+" contains non-ASCII characters")returnurldefunwrap(url):"""Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'. The string is returned unchanged if it's not a wrapped URL. """url=str(url).strip()ifurl[:1]=='<'andurl[-1:]=='>':url=url[1:-1].strip()ifurl[:4]=='URL:':url=url[4:].strip()returnurldefsplittype(url):warnings.warn("urllib.parse.splittype() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splittype(url)_typeprog=Nonedef_splittype(url):"""splittype('type:opaquestring') --> 'type', 'opaquestring'."""global_typeprogif_typeprogisNone:_typeprog=re.compile('([^/:]+):(.*)',re.DOTALL)match=_typeprog.match(url)ifmatch:scheme,data=match.groups()returnscheme.lower(),datareturnNone,urldefsplithost(url):warnings.warn("urllib.parse.splithost() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splithost(url)_hostprog=Nonedef_splithost(url):"""splithost('//host[:port]/path') --> 'host[:port]', '/path'."""global_hostprogif_hostprogisNone:_hostprog=re.compile('//([^/#?]*)(.*)',re.DOTALL)match=_hostprog.match(url)ifmatch:host_port,path=match.groups()ifpathandpath[0]!='/':path='/'+pathreturnhost_port,pathreturnNone,urldefsplituser(host):warnings.warn("urllib.parse.splituser() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splituser(host)def_splituser(host):"""splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""user,delim,host=host.rpartition('@')return(userifdelimelseNone),hostdefsplitpasswd(user):warnings.warn("urllib.parse.splitpasswd() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splitpasswd(user)def_splitpasswd(user):"""splitpasswd('user:passwd') -> 'user', 'passwd'."""user,delim,passwd=user.partition(':')returnuser,(passwdifdelimelseNone)defsplitport(host):warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splitport(host)# splittag('/path#tag') --> '/path', 'tag'_portprog=Nonedef_splitport(host):"""splitport('host:port') --> 'host', 'port'."""global_portprogif_portprogisNone:_portprog=re.compile('(.*):([0-9]*)',re.DOTALL)match=_portprog.fullmatch(host)ifmatch:host,port=match.groups()ifport:returnhost,portreturnhost,Nonedefsplitnport(host,defport=-1):warnings.warn("urllib.parse.splitnport() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splitnport(host,defport)def_splitnport(host,defport=-1):"""Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number is found after ':'. Return None if ':' but not a valid number."""host,delim,port=host.rpartition(':')ifnotdelim:host=portelifport:ifport.isdigit()andport.isascii():nport=int(port)else:nport=Nonereturnhost,nportreturnhost,defportdefsplitquery(url):warnings.warn("urllib.parse.splitquery() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splitquery(url)def_splitquery(url):"""splitquery('/path?query') --> '/path', 'query'."""path,delim,query=url.rpartition('?')ifdelim:returnpath,queryreturnurl,Nonedefsplittag(url):warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splittag(url)def_splittag(url):"""splittag('/path#tag') --> '/path', 'tag'."""path,delim,tag=url.rpartition('#')ifdelim:returnpath,tagreturnurl,Nonedefsplitattr(url):warnings.warn("urllib.parse.splitattr() is deprecated as of 3.8, ""use urllib.parse.urlparse() instead",DeprecationWarning,stacklevel=2)return_splitattr(url)def_splitattr(url):"""splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...]."""words=url.split(';')returnwords[0],words[1:]defsplitvalue(attr):warnings.warn("urllib.parse.splitvalue() is deprecated as of 3.8, ""use urllib.parse.parse_qsl() instead",DeprecationWarning,stacklevel=2)return_splitvalue(attr)def_splitvalue(attr):"""splitvalue('attr=value') --> 'attr', 'value'."""attr,delim,value=attr.partition('=')returnattr,(valueifdelimelseNone)