You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_url.py 71KB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921
  1. # -*- coding: utf-8 -*-
  2. u"""Hyperlink provides Pythonic URL parsing, construction, and rendering.
  3. Usage is straightforward::
  4. >>> from hyperlink import URL
  5. >>> url = URL.from_text(u'http://github.com/mahmoud/hyperlink?utm_source=docs')
  6. >>> url.host
  7. u'github.com'
  8. >>> secure_url = url.replace(scheme=u'https')
  9. >>> secure_url.get('utm_source')[0]
  10. u'docs'
  11. As seen here, the API revolves around the lightweight and immutable
  12. :class:`URL` type, documented below.
  13. """
  14. import re
  15. import sys
  16. import string
  17. import socket
  18. from unicodedata import normalize
  19. try:
  20. from socket import inet_pton
  21. except ImportError:
  22. inet_pton = None # defined below
  23. try:
  24. from collections.abc import Mapping
  25. except ImportError: # Python 2
  26. from collections import Mapping
  27. # Note: IDNAError is a subclass of UnicodeError
  28. from idna import encode as idna_encode, decode as idna_decode, IDNAError
  29. if inet_pton is None:
  30. # based on https://gist.github.com/nnemkin/4966028
  31. # this code only applies on Windows Python 2.7
  32. import ctypes
  33. class _sockaddr(ctypes.Structure):
  34. _fields_ = [("sa_family", ctypes.c_short),
  35. ("__pad1", ctypes.c_ushort),
  36. ("ipv4_addr", ctypes.c_byte * 4),
  37. ("ipv6_addr", ctypes.c_byte * 16),
  38. ("__pad2", ctypes.c_ulong)]
  39. WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA
  40. WSAAddressToStringA = ctypes.windll.ws2_32.WSAAddressToStringA
  41. def inet_pton(address_family, ip_string):
  42. addr = _sockaddr()
  43. ip_string = ip_string.encode('ascii')
  44. addr.sa_family = address_family
  45. addr_size = ctypes.c_int(ctypes.sizeof(addr))
  46. if WSAStringToAddressA(ip_string, address_family, None, ctypes.byref(addr), ctypes.byref(addr_size)) != 0:
  47. raise socket.error(ctypes.FormatError())
  48. if address_family == socket.AF_INET:
  49. return ctypes.string_at(addr.ipv4_addr, 4)
  50. if address_family == socket.AF_INET6:
  51. return ctypes.string_at(addr.ipv6_addr, 16)
  52. raise socket.error('unknown address family')
  53. PY2 = (sys.version_info[0] == 2)
  54. unicode = type(u'')
  55. try:
  56. unichr
  57. except NameError:
  58. unichr = chr # py3
  59. NoneType = type(None)
  60. # from boltons.typeutils
  61. def make_sentinel(name='_MISSING', var_name=None):
  62. """Creates and returns a new **instance** of a new class, suitable for
  63. usage as a "sentinel", a kind of singleton often used to indicate
  64. a value is missing when ``None`` is a valid input.
  65. Args:
  66. name (str): Name of the Sentinel
  67. var_name (str): Set this name to the name of the variable in
  68. its respective module enable pickleability.
  69. >>> make_sentinel(var_name='_MISSING')
  70. _MISSING
  71. The most common use cases here in boltons are as default values
  72. for optional function arguments, partly because of its
  73. less-confusing appearance in automatically generated
  74. documentation. Sentinels also function well as placeholders in queues
  75. and linked lists.
  76. .. note::
  77. By design, additional calls to ``make_sentinel`` with the same
  78. values will not produce equivalent objects.
  79. >>> make_sentinel('TEST') == make_sentinel('TEST')
  80. False
  81. >>> type(make_sentinel('TEST')) == type(make_sentinel('TEST'))
  82. False
  83. """
  84. class Sentinel(object):
  85. def __init__(self):
  86. self.name = name
  87. self.var_name = var_name
  88. def __repr__(self):
  89. if self.var_name:
  90. return self.var_name
  91. return '%s(%r)' % (self.__class__.__name__, self.name)
  92. if var_name:
  93. def __reduce__(self):
  94. return self.var_name
  95. def __nonzero__(self):
  96. return False
  97. __bool__ = __nonzero__
  98. return Sentinel()
  99. _unspecified = _UNSET = make_sentinel('_UNSET')
  100. # RFC 3986 Section 2.3, Unreserved URI Characters
  101. # https://tools.ietf.org/html/rfc3986#section-2.3
  102. _UNRESERVED_CHARS = frozenset('~-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  103. 'abcdefghijklmnopqrstuvwxyz')
  104. # URL parsing regex (based on RFC 3986 Appendix B, with modifications)
  105. _URL_RE = re.compile(r'^((?P<scheme>[^:/?#]+):)?'
  106. r'((?P<_netloc_sep>//)'
  107. r'(?P<authority>[^/?#]*))?'
  108. r'(?P<path>[^?#]*)'
  109. r'(\?(?P<query>[^#]*))?'
  110. r'(#(?P<fragment>.*))?$')
  111. _SCHEME_RE = re.compile(r'^[a-zA-Z0-9+-.]*$')
  112. _AUTHORITY_RE = re.compile(r'^(?:(?P<userinfo>[^@/?#]*)@)?'
  113. r'(?P<host>'
  114. r'(?:\[(?P<ipv6_host>[^[\]/?#]*)\])'
  115. r'|(?P<plain_host>[^:/?#[\]]*)'
  116. r'|(?P<bad_host>.*?))?'
  117. r'(?::(?P<port>.*))?$')
  118. _HEX_CHAR_MAP = dict([((a + b).encode('ascii'),
  119. unichr(int(a + b, 16)).encode('charmap'))
  120. for a in string.hexdigits for b in string.hexdigits])
  121. _ASCII_RE = re.compile('([\x00-\x7f]+)')
  122. # RFC 3986 section 2.2, Reserved Characters
  123. # https://tools.ietf.org/html/rfc3986#section-2.2
  124. _GEN_DELIMS = frozenset(u':/?#[]@')
  125. _SUB_DELIMS = frozenset(u"!$&'()*+,;=")
  126. _ALL_DELIMS = _GEN_DELIMS | _SUB_DELIMS
  127. _USERINFO_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS | set(u'%')
  128. _USERINFO_DELIMS = _ALL_DELIMS - _USERINFO_SAFE
  129. _PATH_SAFE = _USERINFO_SAFE | set(u':@')
  130. _PATH_DELIMS = _ALL_DELIMS - _PATH_SAFE
  131. _SCHEMELESS_PATH_SAFE = _PATH_SAFE - set(':')
  132. _SCHEMELESS_PATH_DELIMS = _ALL_DELIMS - _SCHEMELESS_PATH_SAFE
  133. _FRAGMENT_SAFE = _UNRESERVED_CHARS | _PATH_SAFE | set(u'/?')
  134. _FRAGMENT_DELIMS = _ALL_DELIMS - _FRAGMENT_SAFE
  135. _QUERY_VALUE_SAFE = _UNRESERVED_CHARS | _FRAGMENT_SAFE - set(u'&+')
  136. _QUERY_VALUE_DELIMS = _ALL_DELIMS - _QUERY_VALUE_SAFE
  137. _QUERY_KEY_SAFE = _UNRESERVED_CHARS | _QUERY_VALUE_SAFE - set(u'=')
  138. _QUERY_KEY_DELIMS = _ALL_DELIMS - _QUERY_KEY_SAFE
  139. def _make_decode_map(delims, allow_percent=False):
  140. ret = dict(_HEX_CHAR_MAP)
  141. if not allow_percent:
  142. delims = set(delims) | set([u'%'])
  143. for delim in delims:
  144. _hexord = '{0:02X}'.format(ord(delim)).encode('ascii')
  145. _hexord_lower = _hexord.lower()
  146. ret.pop(_hexord)
  147. if _hexord != _hexord_lower:
  148. ret.pop(_hexord_lower)
  149. return ret
  150. def _make_quote_map(safe_chars):
  151. ret = {}
  152. # v is included in the dict for py3 mostly, because bytestrings
  153. # are iterables of ints, of course!
  154. for i, v in zip(range(256), range(256)):
  155. c = chr(v)
  156. if c in safe_chars:
  157. ret[c] = ret[v] = c
  158. else:
  159. ret[c] = ret[v] = '%{0:02X}'.format(i)
  160. return ret
  161. _USERINFO_PART_QUOTE_MAP = _make_quote_map(_USERINFO_SAFE)
  162. _USERINFO_DECODE_MAP = _make_decode_map(_USERINFO_DELIMS)
  163. _PATH_PART_QUOTE_MAP = _make_quote_map(_PATH_SAFE)
  164. _SCHEMELESS_PATH_PART_QUOTE_MAP = _make_quote_map(_SCHEMELESS_PATH_SAFE)
  165. _PATH_DECODE_MAP = _make_decode_map(_PATH_DELIMS)
  166. _QUERY_KEY_QUOTE_MAP = _make_quote_map(_QUERY_KEY_SAFE)
  167. _QUERY_KEY_DECODE_MAP = _make_decode_map(_QUERY_KEY_DELIMS)
  168. _QUERY_VALUE_QUOTE_MAP = _make_quote_map(_QUERY_VALUE_SAFE)
  169. _QUERY_VALUE_DECODE_MAP = _make_decode_map(_QUERY_VALUE_DELIMS)
  170. _FRAGMENT_QUOTE_MAP = _make_quote_map(_FRAGMENT_SAFE)
  171. _FRAGMENT_DECODE_MAP = _make_decode_map(_FRAGMENT_DELIMS)
  172. _UNRESERVED_QUOTE_MAP = _make_quote_map(_UNRESERVED_CHARS)
  173. _UNRESERVED_DECODE_MAP = dict([(k, v) for k, v in _HEX_CHAR_MAP.items()
  174. if v.decode('ascii', 'replace')
  175. in _UNRESERVED_CHARS])
  176. _ROOT_PATHS = frozenset(((), (u'',)))
  177. def _encode_reserved(text, maximal=True):
  178. """A very comprehensive percent encoding for encoding all
  179. delimiters. Used for arguments to DecodedURL, where a % means a
  180. percent sign, and not the character used by URLs for escaping
  181. bytes.
  182. """
  183. if maximal:
  184. bytestr = normalize('NFC', text).encode('utf8')
  185. return u''.join([_UNRESERVED_QUOTE_MAP[b] for b in bytestr])
  186. return u''.join([_UNRESERVED_QUOTE_MAP[t] if t in _UNRESERVED_CHARS
  187. else t for t in text])
  188. def _encode_path_part(text, maximal=True):
  189. "Percent-encode a single segment of a URL path."
  190. if maximal:
  191. bytestr = normalize('NFC', text).encode('utf8')
  192. return u''.join([_PATH_PART_QUOTE_MAP[b] for b in bytestr])
  193. return u''.join([_PATH_PART_QUOTE_MAP[t] if t in _PATH_DELIMS else t
  194. for t in text])
  195. def _encode_schemeless_path_part(text, maximal=True):
  196. """Percent-encode the first segment of a URL path for a URL without a
  197. scheme specified.
  198. """
  199. if maximal:
  200. bytestr = normalize('NFC', text).encode('utf8')
  201. return u''.join([_SCHEMELESS_PATH_PART_QUOTE_MAP[b] for b in bytestr])
  202. return u''.join([_SCHEMELESS_PATH_PART_QUOTE_MAP[t]
  203. if t in _SCHEMELESS_PATH_DELIMS else t for t in text])
  204. def _encode_path_parts(text_parts, rooted=False, has_scheme=True,
  205. has_authority=True, joined=True, maximal=True):
  206. """
  207. Percent-encode a tuple of path parts into a complete path.
  208. Setting *maximal* to False percent-encodes only the reserved
  209. characters that are syntactically necessary for serialization,
  210. preserving any IRI-style textual data.
  211. Leaving *maximal* set to its default True percent-encodes
  212. everything required to convert a portion of an IRI to a portion of
  213. a URI.
  214. RFC 3986 3.3:
  215. If a URI contains an authority component, then the path component
  216. must either be empty or begin with a slash ("/") character. If a URI
  217. does not contain an authority component, then the path cannot begin
  218. with two slash characters ("//"). In addition, a URI reference
  219. (Section 4.1) may be a relative-path reference, in which case the
  220. first path segment cannot contain a colon (":") character.
  221. """
  222. if not text_parts:
  223. return u'' if joined else text_parts
  224. if rooted:
  225. text_parts = (u'',) + text_parts
  226. # elif has_authority and text_parts:
  227. # raise Exception('see rfc above') # TODO: too late to fail like this?
  228. encoded_parts = []
  229. if has_scheme:
  230. encoded_parts = [_encode_path_part(part, maximal=maximal)
  231. if part else part for part in text_parts]
  232. else:
  233. encoded_parts = [_encode_schemeless_path_part(text_parts[0])]
  234. encoded_parts.extend([_encode_path_part(part, maximal=maximal)
  235. if part else part for part in text_parts[1:]])
  236. if joined:
  237. return u'/'.join(encoded_parts)
  238. return tuple(encoded_parts)
  239. def _encode_query_key(text, maximal=True):
  240. """
  241. Percent-encode a single query string key or value.
  242. """
  243. if maximal:
  244. bytestr = normalize('NFC', text).encode('utf8')
  245. return u''.join([_QUERY_KEY_QUOTE_MAP[b] for b in bytestr])
  246. return u''.join([_QUERY_KEY_QUOTE_MAP[t] if t in _QUERY_KEY_DELIMS else t
  247. for t in text])
  248. def _encode_query_value(text, maximal=True):
  249. """
  250. Percent-encode a single query string key or value.
  251. """
  252. if maximal:
  253. bytestr = normalize('NFC', text).encode('utf8')
  254. return u''.join([_QUERY_VALUE_QUOTE_MAP[b] for b in bytestr])
  255. return u''.join([_QUERY_VALUE_QUOTE_MAP[t]
  256. if t in _QUERY_VALUE_DELIMS else t for t in text])
  257. def _encode_fragment_part(text, maximal=True):
  258. """Quote the fragment part of the URL. Fragments don't have
  259. subdelimiters, so the whole URL fragment can be passed.
  260. """
  261. if maximal:
  262. bytestr = normalize('NFC', text).encode('utf8')
  263. return u''.join([_FRAGMENT_QUOTE_MAP[b] for b in bytestr])
  264. return u''.join([_FRAGMENT_QUOTE_MAP[t] if t in _FRAGMENT_DELIMS else t
  265. for t in text])
  266. def _encode_userinfo_part(text, maximal=True):
  267. """Quote special characters in either the username or password
  268. section of the URL.
  269. """
  270. if maximal:
  271. bytestr = normalize('NFC', text).encode('utf8')
  272. return u''.join([_USERINFO_PART_QUOTE_MAP[b] for b in bytestr])
  273. return u''.join([_USERINFO_PART_QUOTE_MAP[t] if t in _USERINFO_DELIMS
  274. else t for t in text])
  275. # This port list painstakingly curated by hand searching through
  276. # https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  277. # and
  278. # https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
  279. SCHEME_PORT_MAP = {'acap': 674, 'afp': 548, 'dict': 2628, 'dns': 53,
  280. 'file': None, 'ftp': 21, 'git': 9418, 'gopher': 70,
  281. 'http': 80, 'https': 443, 'imap': 143, 'ipp': 631,
  282. 'ipps': 631, 'irc': 194, 'ircs': 6697, 'ldap': 389,
  283. 'ldaps': 636, 'mms': 1755, 'msrp': 2855, 'msrps': None,
  284. 'mtqp': 1038, 'nfs': 111, 'nntp': 119, 'nntps': 563,
  285. 'pop': 110, 'prospero': 1525, 'redis': 6379, 'rsync': 873,
  286. 'rtsp': 554, 'rtsps': 322, 'rtspu': 5005, 'sftp': 22,
  287. 'smb': 445, 'snmp': 161, 'ssh': 22, 'steam': None,
  288. 'svn': 3690, 'telnet': 23, 'ventrilo': 3784, 'vnc': 5900,
  289. 'wais': 210, 'ws': 80, 'wss': 443, 'xmpp': None}
  290. # This list of schemes that don't use authorities is also from the link above.
  291. NO_NETLOC_SCHEMES = set(['urn', 'about', 'bitcoin', 'blob', 'data', 'geo',
  292. 'magnet', 'mailto', 'news', 'pkcs11',
  293. 'sip', 'sips', 'tel'])
  294. # As of Mar 11, 2017, there were 44 netloc schemes, and 13 non-netloc
  295. def register_scheme(text, uses_netloc=True, default_port=None):
  296. """Registers new scheme information, resulting in correct port and
  297. slash behavior from the URL object. There are dozens of standard
  298. schemes preregistered, so this function is mostly meant for
  299. proprietary internal customizations or stopgaps on missing
  300. standards information. If a scheme seems to be missing, please
  301. `file an issue`_!
  302. Args:
  303. text (unicode): Text representing the scheme.
  304. (the 'http' in 'http://hatnote.com')
  305. uses_netloc (bool): Does the scheme support specifying a
  306. network host? For instance, "http" does, "mailto" does
  307. not. Defaults to True.
  308. default_port (int): The default port, if any, for netloc-using
  309. schemes.
  310. .. _file an issue: https://github.com/mahmoud/hyperlink/issues
  311. """
  312. text = text.lower()
  313. if default_port is not None:
  314. try:
  315. default_port = int(default_port)
  316. except (ValueError, TypeError):
  317. raise ValueError('default_port expected integer or None, not %r'
  318. % (default_port,))
  319. if uses_netloc is True:
  320. SCHEME_PORT_MAP[text] = default_port
  321. elif uses_netloc is False:
  322. if default_port is not None:
  323. raise ValueError('unexpected default port while specifying'
  324. ' non-netloc scheme: %r' % default_port)
  325. NO_NETLOC_SCHEMES.add(text)
  326. else:
  327. raise ValueError('uses_netloc expected bool, not: %r' % uses_netloc)
  328. return
  329. def scheme_uses_netloc(scheme, default=None):
  330. """Whether or not a URL uses :code:`:` or :code:`://` to separate the
  331. scheme from the rest of the URL depends on the scheme's own
  332. standard definition. There is no way to infer this behavior
  333. from other parts of the URL. A scheme either supports network
  334. locations or it does not.
  335. The URL type's approach to this is to check for explicitly
  336. registered schemes, with common schemes like HTTP
  337. preregistered. This is the same approach taken by
  338. :mod:`urlparse`.
  339. URL adds two additional heuristics if the scheme as a whole is
  340. not registered. First, it attempts to check the subpart of the
  341. scheme after the last ``+`` character. This adds intuitive
  342. behavior for schemes like ``git+ssh``. Second, if a URL with
  343. an unrecognized scheme is loaded, it will maintain the
  344. separator it sees.
  345. """
  346. if not scheme:
  347. return False
  348. scheme = scheme.lower()
  349. if scheme in SCHEME_PORT_MAP:
  350. return True
  351. if scheme in NO_NETLOC_SCHEMES:
  352. return False
  353. if scheme.split('+')[-1] in SCHEME_PORT_MAP:
  354. return True
  355. return default
  356. class URLParseError(ValueError):
  357. """Exception inheriting from :exc:`ValueError`, raised when failing to
  358. parse a URL. Mostly raised on invalid ports and IPv6 addresses.
  359. """
  360. pass
  361. def _optional(argument, default):
  362. if argument is _UNSET:
  363. return default
  364. else:
  365. return argument
  366. def _typecheck(name, value, *types):
  367. """
  368. Check that the given *value* is one of the given *types*, or raise an
  369. exception describing the problem using *name*.
  370. """
  371. if not types:
  372. raise ValueError('expected one or more types, maybe use _textcheck?')
  373. if not isinstance(value, types):
  374. raise TypeError("expected %s for %s, got %r"
  375. % (" or ".join([t.__name__ for t in types]),
  376. name, value))
  377. return value
  378. def _textcheck(name, value, delims=frozenset(), nullable=False):
  379. if not isinstance(value, unicode):
  380. if nullable and value is None:
  381. return value # used by query string values
  382. else:
  383. str_name = "unicode" if PY2 else "str"
  384. exp = str_name + ' or NoneType' if nullable else str_name
  385. raise TypeError('expected %s for %s, got %r' % (exp, name, value))
  386. if delims and set(value) & set(delims): # TODO: test caching into regexes
  387. raise ValueError('one or more reserved delimiters %s present in %s: %r'
  388. % (''.join(delims), name, value))
  389. return value
  390. def iter_pairs(iterable):
  391. """
  392. Iterate over the (key, value) pairs in ``iterable``.
  393. This handles dictionaries sensibly, and falls back to assuming the
  394. iterable yields (key, value) pairs. This behaviour is similar to
  395. what Python's ``dict()`` constructor does.
  396. """
  397. if isinstance(iterable, Mapping):
  398. iterable = iterable.items()
  399. return iter(iterable)
  400. def _decode_unreserved(text, normalize_case=False, encode_stray_percents=False):
  401. return _percent_decode(text, normalize_case=normalize_case,
  402. encode_stray_percents=encode_stray_percents,
  403. _decode_map=_UNRESERVED_DECODE_MAP)
  404. def _decode_userinfo_part(text, normalize_case=False, encode_stray_percents=False):
  405. return _percent_decode(text, normalize_case=normalize_case,
  406. encode_stray_percents=encode_stray_percents,
  407. _decode_map=_USERINFO_DECODE_MAP)
  408. def _decode_path_part(text, normalize_case=False, encode_stray_percents=False):
  409. """
  410. >>> _decode_path_part(u'%61%77%2f%7a')
  411. u'aw%2fz'
  412. >>> _decode_path_part(u'%61%77%2f%7a', normalize_case=True)
  413. u'aw%2Fz'
  414. """
  415. return _percent_decode(text, normalize_case=normalize_case,
  416. encode_stray_percents=encode_stray_percents,
  417. _decode_map=_PATH_DECODE_MAP)
  418. def _decode_query_key(text, normalize_case=False, encode_stray_percents=False):
  419. return _percent_decode(text, normalize_case=normalize_case,
  420. encode_stray_percents=encode_stray_percents,
  421. _decode_map=_QUERY_KEY_DECODE_MAP)
  422. def _decode_query_value(text, normalize_case=False, encode_stray_percents=False):
  423. return _percent_decode(text, normalize_case=normalize_case,
  424. encode_stray_percents=encode_stray_percents,
  425. _decode_map=_QUERY_VALUE_DECODE_MAP)
  426. def _decode_fragment_part(text, normalize_case=False, encode_stray_percents=False):
  427. return _percent_decode(text, normalize_case=normalize_case,
  428. encode_stray_percents=encode_stray_percents,
  429. _decode_map=_FRAGMENT_DECODE_MAP)
  430. def _percent_decode(text, normalize_case=False, subencoding='utf-8',
  431. raise_subencoding_exc=False, encode_stray_percents=False,
  432. _decode_map=_HEX_CHAR_MAP):
  433. """Convert percent-encoded text characters to their normal,
  434. human-readable equivalents.
  435. All characters in the input text must be encodable by
  436. *subencoding*. All special characters underlying the values in the
  437. percent-encoding must be decodable as *subencoding*. If a
  438. non-*subencoding*-valid string is passed, the original text is
  439. returned with no changes applied.
  440. Only called by field-tailored variants, e.g.,
  441. :func:`_decode_path_part`, as every percent-encodable part of the
  442. URL has characters which should not be percent decoded.
  443. >>> _percent_decode(u'abc%20def')
  444. u'abc def'
  445. Args:
  446. text (unicode): Text with percent-encoding present.
  447. normalize_case (bool): Whether undecoded percent segments, such
  448. as encoded delimiters, should be uppercased, per RFC 3986
  449. Section 2.1. See :func:`_decode_path_part` for an example.
  450. subencoding (unicode): The name of the encoding underlying the
  451. percent-encoding. Pass `False` to get back raw bytes.
  452. raise_subencoding_exc (bool): Whether an error in decoding the bytes
  453. underlying the percent-decoding should be raised.
  454. Returns:
  455. unicode: The percent-decoded version of *text*, decoded by
  456. *subencoding*, unless `subencoding=False` which returns bytes.
  457. """
  458. try:
  459. quoted_bytes = text.encode('utf-8' if subencoding is False else subencoding)
  460. except UnicodeEncodeError:
  461. return text
  462. bits = quoted_bytes.split(b'%')
  463. if len(bits) == 1:
  464. return text
  465. res = [bits[0]]
  466. append = res.append
  467. for item in bits[1:]:
  468. hexpair, rest = item[:2], item[2:]
  469. try:
  470. append(_decode_map[hexpair])
  471. append(rest)
  472. except KeyError:
  473. pair_is_hex = hexpair in _HEX_CHAR_MAP
  474. if pair_is_hex or not encode_stray_percents:
  475. append(b'%')
  476. else:
  477. # if it's undecodable, treat as a real percent sign,
  478. # which is reserved (because it wasn't in the
  479. # context-aware _decode_map passed in), and should
  480. # stay in an encoded state.
  481. append(b'%25')
  482. if normalize_case and pair_is_hex:
  483. append(hexpair.upper())
  484. append(rest)
  485. else:
  486. append(item)
  487. unquoted_bytes = b''.join(res)
  488. if subencoding is False:
  489. return unquoted_bytes
  490. try:
  491. return unquoted_bytes.decode(subencoding)
  492. except UnicodeDecodeError:
  493. if raise_subencoding_exc:
  494. raise
  495. return text
  496. def _decode_host(host):
  497. """Decode a host from ASCII-encodable text to IDNA-decoded text. If
  498. the host text is not ASCII, it is returned unchanged, as it is
  499. presumed that it is already IDNA-decoded.
  500. Some technical details: _decode_host is built on top of the "idna"
  501. package, which has some quirks:
  502. Capital letters are not valid IDNA2008. The idna package will
  503. raise an exception like this on capital letters:
  504. > idna.core.InvalidCodepoint: Codepoint U+004B at position 1 ... not allowed
  505. However, if a segment of a host (i.e., something in
  506. url.host.split('.')) is already ASCII, idna doesn't perform its
  507. usual checks. In fact, for capital letters it automatically
  508. lowercases them.
  509. This check and some other functionality can be bypassed by passing
  510. uts46=True to idna.encode/decode. This allows a more permissive and
  511. convenient interface. So far it seems like the balanced approach.
  512. Example output (from idna==2.6):
  513. >> idna.encode(u'mahmöud.io')
  514. 'xn--mahmud-zxa.io'
  515. >> idna.encode(u'Mahmöud.io')
  516. Traceback (most recent call last):
  517. File "<stdin>", line 1, in <module>
  518. File "/home/mahmoud/virtualenvs/hyperlink/local/lib/python2.7/site-packages/idna/core.py", line 355, in encode
  519. result.append(alabel(label))
  520. File "/home/mahmoud/virtualenvs/hyperlink/local/lib/python2.7/site-packages/idna/core.py", line 276, in alabel
  521. check_label(label)
  522. File "/home/mahmoud/virtualenvs/hyperlink/local/lib/python2.7/site-packages/idna/core.py", line 253, in check_label
  523. raise InvalidCodepoint('Codepoint {0} at position {1} of {2} not allowed'.format(_unot(cp_value), pos+1, repr(label)))
  524. idna.core.InvalidCodepoint: Codepoint U+004D at position 1 of u'Mahm\xf6ud' not allowed
  525. >> idna.encode(u'Mahmoud.io')
  526. 'Mahmoud.io'
  527. # Similar behavior for decodes below
  528. >> idna.decode(u'Mahmoud.io')
  529. u'mahmoud.io
  530. >> idna.decode(u'Méhmoud.io', uts46=True)
  531. u'm\xe9hmoud.io'
  532. """
  533. if not host:
  534. return u''
  535. try:
  536. host_bytes = host.encode("ascii")
  537. except UnicodeEncodeError:
  538. host_text = host
  539. else:
  540. try:
  541. host_text = idna_decode(host_bytes, uts46=True)
  542. except ValueError:
  543. # only reached on "narrow" (UCS-2) Python builds <3.4, see #7
  544. # NOTE: not going to raise here, because there's no
  545. # ambiguity in the IDNA, and the host is still
  546. # technically usable
  547. host_text = host
  548. return host_text
  549. def _resolve_dot_segments(path):
  550. """Normalize the URL path by resolving segments of '.' and '..'. For
  551. more details, see `RFC 3986 section 5.2.4, Remove Dot Segments`_.
  552. Args:
  553. path (list): path segments in string form
  554. Returns:
  555. list: a new list of path segments with the '.' and '..' elements
  556. removed and resolved.
  557. .. _RFC 3986 section 5.2.4, Remove Dot Segments: https://tools.ietf.org/html/rfc3986#section-5.2.4
  558. """
  559. segs = []
  560. for seg in path:
  561. if seg == u'.':
  562. pass
  563. elif seg == u'..':
  564. if segs:
  565. segs.pop()
  566. else:
  567. segs.append(seg)
  568. if list(path[-1:]) in ([u'.'], [u'..']):
  569. segs.append(u'')
  570. return segs
  571. def parse_host(host):
  572. """Parse the host into a tuple of ``(family, host)``, where family
  573. is the appropriate :mod:`socket` module constant when the host is
  574. an IP address. Family is ``None`` when the host is not an IP.
  575. Will raise :class:`URLParseError` on invalid IPv6 constants.
  576. Returns:
  577. tuple: family (socket constant or None), host (string)
  578. >>> parse_host('googlewebsite.com') == (None, 'googlewebsite.com')
  579. True
  580. >>> parse_host('::1') == (socket.AF_INET6, '::1')
  581. True
  582. >>> parse_host('192.168.1.1') == (socket.AF_INET, '192.168.1.1')
  583. True
  584. """
  585. if not host:
  586. return None, u''
  587. if u':' in host:
  588. try:
  589. inet_pton(socket.AF_INET6, host)
  590. except socket.error as se:
  591. raise URLParseError('invalid IPv6 host: %r (%r)' % (host, se))
  592. except UnicodeEncodeError:
  593. pass # TODO: this can't be a real host right?
  594. else:
  595. family = socket.AF_INET6
  596. return family, host
  597. try:
  598. inet_pton(socket.AF_INET, host)
  599. except (socket.error, UnicodeEncodeError):
  600. family = None # not an IP
  601. else:
  602. family = socket.AF_INET
  603. return family, host
  604. class URL(object):
  605. """From blogs to billboards, URLs are so common, that it's easy to
  606. overlook their complexity and power. With hyperlink's
  607. :class:`URL` type, working with URLs doesn't have to be hard.
  608. URLs are made of many parts. Most of these parts are officially
  609. named in `RFC 3986`_ and this diagram may prove handy in identifying
  610. them::
  611. foo://user:pass@example.com:8042/over/there?name=ferret#nose
  612. \_/ \_______/ \_________/ \__/\_________/ \_________/ \__/
  613. | | | | | | |
  614. scheme userinfo host port path query fragment
  615. While :meth:`~URL.from_text` is used for parsing whole URLs, the
  616. :class:`URL` constructor builds a URL from the individual
  617. components, like so::
  618. >>> from hyperlink import URL
  619. >>> url = URL(scheme=u'https', host=u'example.com', path=[u'hello', u'world'])
  620. >>> print(url.to_text())
  621. https://example.com/hello/world
  622. The constructor runs basic type checks. All strings are expected
  623. to be decoded (:class:`unicode` in Python 2). All arguments are
  624. optional, defaulting to appropriately empty values. A full list of
  625. constructor arguments is below.
  626. Args:
  627. scheme (unicode): The text name of the scheme.
  628. host (unicode): The host portion of the network location
  629. port (int): The port part of the network location. If
  630. ``None`` or no port is passed, the port will default to
  631. the default port of the scheme, if it is known. See the
  632. ``SCHEME_PORT_MAP`` and :func:`register_default_port`
  633. for more info.
  634. path (tuple): A tuple of strings representing the
  635. slash-separated parts of the path.
  636. query (tuple): The query parameters, as a dictionary or
  637. as an iterable of key-value pairs.
  638. fragment (unicode): The fragment part of the URL.
  639. rooted (bool): Whether or not the path begins with a slash.
  640. userinfo (unicode): The username or colon-separated
  641. username:password pair.
  642. uses_netloc (bool): Indicates whether two slashes appear
  643. between the scheme and the host (``http://eg.com`` vs
  644. ``mailto:e@g.com``). Set automatically based on scheme.
  645. All of these parts are also exposed as read-only attributes of
  646. URL instances, along with several useful methods.
  647. .. _RFC 3986: https://tools.ietf.org/html/rfc3986
  648. .. _RFC 3987: https://tools.ietf.org/html/rfc3987
  649. """
  650. def __init__(self, scheme=None, host=None, path=(), query=(), fragment=u'',
  651. port=None, rooted=None, userinfo=u'', uses_netloc=None):
  652. if host is not None and scheme is None:
  653. scheme = u'http' # TODO: why
  654. if port is None:
  655. port = SCHEME_PORT_MAP.get(scheme)
  656. if host and query and not path:
  657. # per RFC 3986 6.2.3, "a URI that uses the generic syntax
  658. # for authority with an empty path should be normalized to
  659. # a path of '/'."
  660. path = (u'',)
  661. # Now that we're done detecting whether they were passed, we can set
  662. # them to their defaults:
  663. if scheme is None:
  664. scheme = u''
  665. if host is None:
  666. host = u''
  667. if rooted is None:
  668. rooted = bool(host)
  669. # Set attributes.
  670. self._scheme = _textcheck("scheme", scheme)
  671. if self._scheme:
  672. if not _SCHEME_RE.match(self._scheme):
  673. raise ValueError('invalid scheme: %r. Only alphanumeric, "+",'
  674. ' "-", and "." allowed. Did you meant to call'
  675. ' %s.from_text()?'
  676. % (self._scheme, self.__class__.__name__))
  677. _, self._host = parse_host(_textcheck('host', host, '/?#@'))
  678. if isinstance(path, unicode):
  679. raise TypeError("expected iterable of text for path, not: %r"
  680. % (path,))
  681. self._path = tuple((_textcheck("path segment", segment, '/?#')
  682. for segment in path))
  683. self._query = tuple(
  684. (_textcheck("query parameter name", k, '&=#'),
  685. _textcheck("query parameter value", v, '&#', nullable=True))
  686. for k, v in iter_pairs(query))
  687. self._fragment = _textcheck("fragment", fragment)
  688. self._port = _typecheck("port", port, int, NoneType)
  689. self._rooted = _typecheck("rooted", rooted, bool)
  690. self._userinfo = _textcheck("userinfo", userinfo, '/?#@')
  691. uses_netloc = scheme_uses_netloc(self._scheme, uses_netloc)
  692. self._uses_netloc = _typecheck("uses_netloc",
  693. uses_netloc, bool, NoneType)
  694. return
  695. def get_decoded_url(self, lazy=False):
  696. try:
  697. return self._decoded_url
  698. except AttributeError:
  699. self._decoded_url = DecodedURL(self, lazy=lazy)
  700. return self._decoded_url
  701. @property
  702. def scheme(self):
  703. """The scheme is a string, and the first part of an absolute URL, the
  704. part before the first colon, and the part which defines the
  705. semantics of the rest of the URL. Examples include "http",
  706. "https", "ssh", "file", "mailto", and many others. See
  707. :func:`~hyperlink.register_scheme()` for more info.
  708. """
  709. return self._scheme
  710. @property
  711. def host(self):
  712. """The host is a string, and the second standard part of an absolute
  713. URL. When present, a valid host must be a domain name, or an
  714. IP (v4 or v6). It occurs before the first slash, or the second
  715. colon, if a :attr:`~hyperlink.URL.port` is provided.
  716. """
  717. return self._host
  718. @property
  719. def port(self):
  720. """The port is an integer that is commonly used in connecting to the
  721. :attr:`host`, and almost never appears without it.
  722. When not present in the original URL, this attribute defaults
  723. to the scheme's default port. If the scheme's default port is
  724. not known, and the port is not provided, this attribute will
  725. be set to None.
  726. >>> URL.from_text(u'http://example.com/pa/th').port
  727. 80
  728. >>> URL.from_text(u'foo://example.com/pa/th').port
  729. >>> URL.from_text(u'foo://example.com:8042/pa/th').port
  730. 8042
  731. .. note::
  732. Per the standard, when the port is the same as the schemes
  733. default port, it will be omitted in the text URL.
  734. """
  735. return self._port
  736. @property
  737. def path(self):
  738. """A tuple of strings, created by splitting the slash-separated
  739. hierarchical path. Started by the first slash after the host,
  740. terminated by a "?", which indicates the start of the
  741. :attr:`~hyperlink.URL.query` string.
  742. """
  743. return self._path
  744. @property
  745. def query(self):
  746. """Tuple of pairs, created by splitting the ampersand-separated
  747. mapping of keys and optional values representing
  748. non-hierarchical data used to identify the resource. Keys are
  749. always strings. Values are strings when present, or None when
  750. missing.
  751. For more operations on the mapping, see
  752. :meth:`~hyperlink.URL.get()`, :meth:`~hyperlink.URL.add()`,
  753. :meth:`~hyperlink.URL.set()`, and
  754. :meth:`~hyperlink.URL.delete()`.
  755. """
  756. return self._query
  757. @property
  758. def fragment(self):
  759. """A string, the last part of the URL, indicated by the first "#"
  760. after the :attr:`~hyperlink.URL.path` or
  761. :attr:`~hyperlink.URL.query`. Enables indirect identification
  762. of a secondary resource, like an anchor within an HTML page.
  763. """
  764. return self._fragment
  765. @property
  766. def rooted(self):
  767. """Whether or not the path starts with a forward slash (``/``).
  768. This is taken from the terminology in the BNF grammar,
  769. specifically the "path-rootless", rule, since "absolute path"
  770. and "absolute URI" are somewhat ambiguous. :attr:`path` does
  771. not contain the implicit prefixed ``"/"`` since that is
  772. somewhat awkward to work with.
  773. """
  774. return self._rooted
  775. @property
  776. def userinfo(self):
  777. """The colon-separated string forming the username-password
  778. combination.
  779. """
  780. return self._userinfo
  781. @property
  782. def uses_netloc(self):
  783. """
  784. """
  785. return self._uses_netloc
  786. @property
  787. def user(self):
  788. """
  789. The user portion of :attr:`~hyperlink.URL.userinfo`.
  790. """
  791. return self.userinfo.split(u':')[0]
  792. def authority(self, with_password=False, **kw):
  793. """Compute and return the appropriate host/port/userinfo combination.
  794. >>> url = URL.from_text(u'http://user:pass@localhost:8080/a/b?x=y')
  795. >>> url.authority()
  796. u'user:@localhost:8080'
  797. >>> url.authority(with_password=True)
  798. u'user:pass@localhost:8080'
  799. Args:
  800. with_password (bool): Whether the return value of this
  801. method include the password in the URL, if it is
  802. set. Defaults to False.
  803. Returns:
  804. str: The authority (network location and user information) portion
  805. of the URL.
  806. """
  807. # first, a bit of twisted compat
  808. with_password = kw.pop('includeSecrets', with_password)
  809. if kw:
  810. raise TypeError('got unexpected keyword arguments: %r' % kw.keys())
  811. host = self.host
  812. if ':' in host:
  813. hostport = ['[' + host + ']']
  814. else:
  815. hostport = [self.host]
  816. if self.port != SCHEME_PORT_MAP.get(self.scheme):
  817. hostport.append(unicode(self.port))
  818. authority = []
  819. if self.userinfo:
  820. userinfo = self.userinfo
  821. if not with_password and u":" in userinfo:
  822. userinfo = userinfo[:userinfo.index(u":") + 1]
  823. authority.append(userinfo)
  824. authority.append(u":".join(hostport))
  825. return u"@".join(authority)
  826. def __eq__(self, other):
  827. if not isinstance(other, self.__class__):
  828. return NotImplemented
  829. for attr in ['scheme', 'userinfo', 'host', 'query',
  830. 'fragment', 'port', 'uses_netloc']:
  831. if getattr(self, attr) != getattr(other, attr):
  832. return False
  833. if self.path == other.path or (self.path in _ROOT_PATHS
  834. and other.path in _ROOT_PATHS):
  835. return True
  836. return False
  837. def __ne__(self, other):
  838. if not isinstance(other, self.__class__):
  839. return NotImplemented
  840. return not self.__eq__(other)
  841. def __hash__(self):
  842. return hash((self.__class__, self.scheme, self.userinfo, self.host,
  843. self.path, self.query, self.fragment, self.port,
  844. self.rooted, self.uses_netloc))
  845. @property
  846. def absolute(self):
  847. """Whether or not the URL is "absolute". Absolute URLs are complete
  848. enough to resolve to a network resource without being relative
  849. to a base URI.
  850. >>> URL.from_text(u'http://wikipedia.org/').absolute
  851. True
  852. >>> URL.from_text(u'?a=b&c=d').absolute
  853. False
  854. Absolute URLs must have both a scheme and a host set.
  855. """
  856. return bool(self.scheme and self.host)
  857. def replace(self, scheme=_UNSET, host=_UNSET, path=_UNSET, query=_UNSET,
  858. fragment=_UNSET, port=_UNSET, rooted=_UNSET, userinfo=_UNSET,
  859. uses_netloc=_UNSET):
  860. """:class:`URL` objects are immutable, which means that attributes
  861. are designed to be set only once, at construction. Instead of
  862. modifying an existing URL, one simply creates a copy with the
  863. desired changes.
  864. If any of the following arguments is omitted, it defaults to
  865. the value on the current URL.
  866. Args:
  867. scheme (unicode): The text name of the scheme.
  868. host (unicode): The host portion of the network location
  869. port (int): The port part of the network location.
  870. path (tuple): A tuple of strings representing the
  871. slash-separated parts of the path.
  872. query (tuple): The query parameters, as a tuple of
  873. key-value pairs.
  874. query (tuple): The query parameters, as a dictionary or
  875. as an iterable of key-value pairs.
  876. fragment (unicode): The fragment part of the URL.
  877. rooted (bool): Whether or not the path begins with a slash.
  878. userinfo (unicode): The username or colon-separated
  879. username:password pair.
  880. uses_netloc (bool): Indicates whether two slashes appear
  881. between the scheme and the host (``http://eg.com`` vs
  882. ``mailto:e@g.com``)
  883. Returns:
  884. URL: a copy of the current :class:`URL`, with new values for
  885. parameters passed.
  886. """
  887. return self.__class__(
  888. scheme=_optional(scheme, self.scheme),
  889. host=_optional(host, self.host),
  890. path=_optional(path, self.path),
  891. query=_optional(query, self.query),
  892. fragment=_optional(fragment, self.fragment),
  893. port=_optional(port, self.port),
  894. rooted=_optional(rooted, self.rooted),
  895. userinfo=_optional(userinfo, self.userinfo),
  896. uses_netloc=_optional(uses_netloc, self.uses_netloc)
  897. )
  898. @classmethod
  899. def from_text(cls, text):
  900. """Whereas the :class:`URL` constructor is useful for constructing
  901. URLs from parts, :meth:`~URL.from_text` supports parsing whole
  902. URLs from their string form::
  903. >>> URL.from_text(u'http://example.com')
  904. URL.from_text(u'http://example.com')
  905. >>> URL.from_text(u'?a=b&x=y')
  906. URL.from_text(u'?a=b&x=y')
  907. As you can see above, it's also used as the :func:`repr` of
  908. :class:`URL` objects. The natural counterpart to
  909. :func:`~URL.to_text()`. This method only accepts *text*, so be
  910. sure to decode those bytestrings.
  911. Args:
  912. text (unicode): A valid URL string.
  913. Returns:
  914. URL: The structured object version of the parsed string.
  915. .. note::
  916. Somewhat unexpectedly, URLs are a far more permissive
  917. format than most would assume. Many strings which don't
  918. look like URLs are still valid URLs. As a result, this
  919. method only raises :class:`URLParseError` on invalid port
  920. and IPv6 values in the host portion of the URL.
  921. """
  922. um = _URL_RE.match(_textcheck('text', text))
  923. try:
  924. gs = um.groupdict()
  925. except AttributeError:
  926. raise URLParseError('could not parse url: %r' % text)
  927. au_text = gs['authority'] or u''
  928. au_m = _AUTHORITY_RE.match(au_text)
  929. try:
  930. au_gs = au_m.groupdict()
  931. except AttributeError:
  932. raise URLParseError('invalid authority %r in url: %r'
  933. % (au_text, text))
  934. if au_gs['bad_host']:
  935. raise URLParseError('invalid host %r in url: %r'
  936. % (au_gs['bad_host'], text))
  937. userinfo = au_gs['userinfo'] or u''
  938. host = au_gs['ipv6_host'] or au_gs['plain_host']
  939. port = au_gs['port']
  940. if port is not None:
  941. try:
  942. port = int(port)
  943. except ValueError:
  944. if not port: # TODO: excessive?
  945. raise URLParseError('port must not be empty: %r' % au_text)
  946. raise URLParseError('expected integer for port, not %r' % port)
  947. scheme = gs['scheme'] or u''
  948. fragment = gs['fragment'] or u''
  949. uses_netloc = bool(gs['_netloc_sep'])
  950. if gs['path']:
  951. path = gs['path'].split(u"/")
  952. if not path[0]:
  953. path.pop(0)
  954. rooted = True
  955. else:
  956. rooted = False
  957. else:
  958. path = ()
  959. rooted = bool(au_text)
  960. if gs['query']:
  961. query = ((qe.split(u"=", 1) if u'=' in qe else (qe, None))
  962. for qe in gs['query'].split(u"&"))
  963. else:
  964. query = ()
  965. return cls(scheme, host, path, query, fragment, port,
  966. rooted, userinfo, uses_netloc)
  967. def normalize(self, scheme=True, host=True, path=True, query=True,
  968. fragment=True, userinfo=True, percents=True):
  969. """Return a new URL object with several standard normalizations
  970. applied:
  971. * Decode unreserved characters (`RFC 3986 2.3`_)
  972. * Uppercase remaining percent-encoded octets (`RFC 3986 2.1`_)
  973. * Convert scheme and host casing to lowercase (`RFC 3986 3.2.2`_)
  974. * Resolve any "." and ".." references in the path (`RFC 3986 6.2.2.3`_)
  975. * Ensure an ending slash on URLs with an empty path (`RFC 3986 6.2.3`_)
  976. * Encode any stray percent signs (`%`) in percent-encoded
  977. fields (path, query, fragment, userinfo) (`RFC 3986 2.4`_)
  978. All are applied by default, but normalizations can be disabled
  979. per-part by passing `False` for that part's corresponding
  980. name.
  981. Args:
  982. scheme (bool): Convert the scheme to lowercase
  983. host (bool): Convert the host to lowercase
  984. path (bool): Normalize the path (see above for details)
  985. query (bool): Normalize the query string
  986. fragment (bool): Normalize the fragment
  987. userinfo (bool): Normalize the userinfo
  988. percents (bool): Encode isolated percent signs
  989. for any percent-encoded fields which are being
  990. normalized (defaults to True).
  991. >>> url = URL.from_text(u'Http://example.COM/a/../b/./c%2f?%61%')
  992. >>> print(url.normalize().to_text())
  993. http://example.com/b/c%2F?a%25
  994. .. _RFC 3986 3.2.2: https://tools.ietf.org/html/rfc3986#section-3.2.2
  995. .. _RFC 3986 2.3: https://tools.ietf.org/html/rfc3986#section-2.3
  996. .. _RFC 3986 2.1: https://tools.ietf.org/html/rfc3986#section-2.1
  997. .. _RFC 3986 6.2.2.3: https://tools.ietf.org/html/rfc3986#section-6.2.2.3
  998. .. _RFC 3986 6.2.3: https://tools.ietf.org/html/rfc3986#section-6.2.3
  999. .. _RFC 3986 2.4: https://tools.ietf.org/html/rfc3986#section-2.4
  1000. """
  1001. kw = {}
  1002. if scheme:
  1003. kw['scheme'] = self.scheme.lower()
  1004. if host:
  1005. kw['host'] = self.host.lower()
  1006. def _dec_unres(target):
  1007. return _decode_unreserved(target, normalize_case=True,
  1008. encode_stray_percents=percents)
  1009. if path:
  1010. if self.path:
  1011. kw['path'] = [_dec_unres(p) for p in _resolve_dot_segments(self.path)]
  1012. else:
  1013. kw['path'] = (u'',)
  1014. if query:
  1015. kw['query'] = [(_dec_unres(k), _dec_unres(v) if v else v)
  1016. for k, v in self.query]
  1017. if fragment:
  1018. kw['fragment'] = _dec_unres(self.fragment)
  1019. if userinfo:
  1020. kw['userinfo'] = u':'.join([_dec_unres(p)
  1021. for p in self.userinfo.split(':', 1)])
  1022. return self.replace(**kw)
  1023. def child(self, *segments):
  1024. """Make a new :class:`URL` where the given path segments are a child
  1025. of this URL, preserving other parts of the URL, including the
  1026. query string and fragment.
  1027. For example::
  1028. >>> url = URL.from_text(u'http://localhost/a/b?x=y')
  1029. >>> child_url = url.child(u"c", u"d")
  1030. >>> child_url.to_text()
  1031. u'http://localhost/a/b/c/d?x=y'
  1032. Args:
  1033. segments (unicode): Additional parts to be joined and added to
  1034. the path, like :func:`os.path.join`. Special characters
  1035. in segments will be percent encoded.
  1036. Returns:
  1037. URL: A copy of the current URL with the extra path segments.
  1038. """
  1039. if not segments:
  1040. return self
  1041. segments = [_textcheck('path segment', s) for s in segments]
  1042. new_segs = _encode_path_parts(segments, joined=False, maximal=False)
  1043. new_path = self.path[:-1 if (self.path and self.path[-1] == u'')
  1044. else None] + new_segs
  1045. return self.replace(path=new_path)
  1046. def sibling(self, segment):
  1047. """Make a new :class:`URL` with a single path segment that is a
  1048. sibling of this URL path.
  1049. Args:
  1050. segment (unicode): A single path segment.
  1051. Returns:
  1052. URL: A copy of the current URL with the last path segment
  1053. replaced by *segment*. Special characters such as
  1054. ``/?#`` will be percent encoded.
  1055. """
  1056. _textcheck('path segment', segment)
  1057. new_path = self.path[:-1] + (_encode_path_part(segment),)
  1058. return self.replace(path=new_path)
  1059. def click(self, href=u''):
  1060. """Resolve the given URL relative to this URL.
  1061. The resulting URI should match what a web browser would
  1062. generate if you visited the current URL and clicked on *href*.
  1063. >>> url = URL.from_text(u'http://blog.hatnote.com/')
  1064. >>> url.click(u'/post/155074058790').to_text()
  1065. u'http://blog.hatnote.com/post/155074058790'
  1066. >>> url = URL.from_text(u'http://localhost/a/b/c/')
  1067. >>> url.click(u'../d/./e').to_text()
  1068. u'http://localhost/a/b/d/e'
  1069. Args:
  1070. href (unicode): A string representing a clicked URL.
  1071. Return:
  1072. URL: A copy of the current URL with navigation logic applied.
  1073. For more information, see `RFC 3986 section 5`_.
  1074. .. _RFC 3986 section 5: https://tools.ietf.org/html/rfc3986#section-5
  1075. """
  1076. if href:
  1077. if isinstance(href, URL):
  1078. clicked = href
  1079. else:
  1080. # TODO: This error message is not completely accurate,
  1081. # as URL objects are now also valid, but Twisted's
  1082. # test suite (wrongly) relies on this exact message.
  1083. _textcheck('relative URL', href)
  1084. clicked = URL.from_text(href)
  1085. if clicked.absolute:
  1086. return clicked
  1087. else:
  1088. clicked = self
  1089. query = clicked.query
  1090. if clicked.scheme and not clicked.rooted:
  1091. # Schemes with relative paths are not well-defined. RFC 3986 calls
  1092. # them a "loophole in prior specifications" that should be avoided,
  1093. # or supported only for backwards compatibility.
  1094. raise NotImplementedError('absolute URI with rootless path: %r'
  1095. % (href,))
  1096. else:
  1097. if clicked.rooted:
  1098. path = clicked.path
  1099. elif clicked.path:
  1100. path = self.path[:-1] + clicked.path
  1101. else:
  1102. path = self.path
  1103. if not query:
  1104. query = self.query
  1105. return self.replace(scheme=clicked.scheme or self.scheme,
  1106. host=clicked.host or self.host,
  1107. port=clicked.port or self.port,
  1108. path=_resolve_dot_segments(path),
  1109. query=query,
  1110. fragment=clicked.fragment)
  1111. def to_uri(self):
  1112. u"""Make a new :class:`URL` instance with all non-ASCII characters
  1113. appropriately percent-encoded. This is useful to do in preparation
  1114. for sending a :class:`URL` over a network protocol.
  1115. For example::
  1116. >>> URL.from_text(u'https://ايران.com/foo⇧bar/').to_uri()
  1117. URL.from_text(u'https://xn--mgba3a4fra.com/foo%E2%87%A7bar/')
  1118. Returns:
  1119. URL: A new instance with its path segments, query parameters, and
  1120. hostname encoded, so that they are all in the standard
  1121. US-ASCII range.
  1122. """
  1123. new_userinfo = u':'.join([_encode_userinfo_part(p) for p in
  1124. self.userinfo.split(':', 1)])
  1125. new_path = _encode_path_parts(self.path, has_scheme=bool(self.scheme),
  1126. rooted=False, joined=False, maximal=True)
  1127. new_host = self.host if not self.host else idna_encode(self.host, uts46=True).decode("ascii")
  1128. return self.replace(
  1129. userinfo=new_userinfo,
  1130. host=new_host,
  1131. path=new_path,
  1132. query=tuple([(_encode_query_key(k, maximal=True),
  1133. _encode_query_value(v, maximal=True)
  1134. if v is not None else None)
  1135. for k, v in self.query]),
  1136. fragment=_encode_fragment_part(self.fragment, maximal=True)
  1137. )
  1138. def to_iri(self):
  1139. u"""Make a new :class:`URL` instance with all but a few reserved
  1140. characters decoded into human-readable format.
  1141. Percent-encoded Unicode and IDNA-encoded hostnames are
  1142. decoded, like so::
  1143. >>> url = URL.from_text(u'https://xn--mgba3a4fra.example.com/foo%E2%87%A7bar/')
  1144. >>> print(url.to_iri().to_text())
  1145. https://ايران.example.com/foo⇧bar/
  1146. .. note::
  1147. As a general Python issue, "narrow" (UCS-2) builds of
  1148. Python may not be able to fully decode certain URLs, and
  1149. the in those cases, this method will return a best-effort,
  1150. partially-decoded, URL which is still valid. This issue
  1151. does not affect any Python builds 3.4+.
  1152. Returns:
  1153. URL: A new instance with its path segments, query parameters, and
  1154. hostname decoded for display purposes.
  1155. """
  1156. new_userinfo = u':'.join([_decode_userinfo_part(p) for p in
  1157. self.userinfo.split(':', 1)])
  1158. host_text = _decode_host(self.host)
  1159. return self.replace(userinfo=new_userinfo,
  1160. host=host_text,
  1161. path=[_decode_path_part(segment)
  1162. for segment in self.path],
  1163. query=[(_decode_query_key(k),
  1164. _decode_query_value(v)
  1165. if v is not None else None)
  1166. for k, v in self.query],
  1167. fragment=_decode_fragment_part(self.fragment))
  1168. def to_text(self, with_password=False):
  1169. """Render this URL to its textual representation.
  1170. By default, the URL text will *not* include a password, if one
  1171. is set. RFC 3986 considers using URLs to represent such
  1172. sensitive information as deprecated. Quoting from RFC 3986,
  1173. `section 3.2.1`:
  1174. "Applications should not render as clear text any data after the
  1175. first colon (":") character found within a userinfo subcomponent
  1176. unless the data after the colon is the empty string (indicating no
  1177. password)."
  1178. Args:
  1179. with_password (bool): Whether or not to include the
  1180. password in the URL text. Defaults to False.
  1181. Returns:
  1182. str: The serialized textual representation of this URL,
  1183. such as ``u"http://example.com/some/path?some=query"``.
  1184. The natural counterpart to :class:`URL.from_text()`.
  1185. .. _section 3.2.1: https://tools.ietf.org/html/rfc3986#section-3.2.1
  1186. """
  1187. scheme = self.scheme
  1188. authority = self.authority(with_password)
  1189. path = _encode_path_parts(self.path,
  1190. rooted=self.rooted,
  1191. has_scheme=bool(scheme),
  1192. has_authority=bool(authority),
  1193. maximal=False)
  1194. query_parts = []
  1195. for k, v in self.query:
  1196. if v is None:
  1197. query_parts.append(_encode_query_key(k, maximal=False))
  1198. else:
  1199. query_parts.append(u'='.join((_encode_query_key(k, maximal=False),
  1200. _encode_query_value(v, maximal=False))))
  1201. query_string = u'&'.join(query_parts)
  1202. fragment = self.fragment
  1203. parts = []
  1204. _add = parts.append
  1205. if scheme:
  1206. _add(scheme)
  1207. _add(':')
  1208. if authority:
  1209. _add('//')
  1210. _add(authority)
  1211. elif (scheme and path[:2] != '//' and self.uses_netloc):
  1212. _add('//')
  1213. if path:
  1214. if scheme and authority and path[:1] != '/':
  1215. _add('/') # relpaths with abs authorities auto get '/'
  1216. _add(path)
  1217. if query_string:
  1218. _add('?')
  1219. _add(query_string)
  1220. if fragment:
  1221. _add('#')
  1222. _add(fragment)
  1223. return u''.join(parts)
  1224. def __repr__(self):
  1225. """Convert this URL to an representation that shows all of its
  1226. constituent parts, as well as being a valid argument to
  1227. :func:`eval`.
  1228. """
  1229. return '%s.from_text(%r)' % (self.__class__.__name__, self.to_text())
  1230. def _to_bytes(self):
  1231. """
  1232. Allows for direct usage of URL objects with libraries like
  1233. requests, which automatically stringify URL parameters. See
  1234. issue #49.
  1235. """
  1236. return self.to_uri().to_text().encode('ascii')
  1237. if PY2:
  1238. __str__ = _to_bytes
  1239. __unicode__ = to_text
  1240. else:
  1241. __bytes__ = _to_bytes
  1242. __str__ = to_text
  1243. # # Begin Twisted Compat Code
  1244. asURI = to_uri
  1245. asIRI = to_iri
  1246. @classmethod
  1247. def fromText(cls, s):
  1248. return cls.from_text(s)
  1249. def asText(self, includeSecrets=False):
  1250. return self.to_text(with_password=includeSecrets)
  1251. def __dir__(self):
  1252. try:
  1253. ret = object.__dir__(self)
  1254. except AttributeError:
  1255. # object.__dir__ == AttributeError # pdw for py2
  1256. ret = dir(self.__class__) + list(self.__dict__.keys())
  1257. ret = sorted(set(ret) - set(['fromText', 'asURI', 'asIRI', 'asText']))
  1258. return ret
  1259. # # End Twisted Compat Code
  1260. def add(self, name, value=None):
  1261. """Make a new :class:`URL` instance with a given query argument,
  1262. *name*, added to it with the value *value*, like so::
  1263. >>> URL.from_text(u'https://example.com/?x=y').add(u'x')
  1264. URL.from_text(u'https://example.com/?x=y&x')
  1265. >>> URL.from_text(u'https://example.com/?x=y').add(u'x', u'z')
  1266. URL.from_text(u'https://example.com/?x=y&x=z')
  1267. Args:
  1268. name (unicode): The name of the query parameter to add. The
  1269. part before the ``=``.
  1270. value (unicode): The value of the query parameter to add. The
  1271. part after the ``=``. Defaults to ``None``, meaning no
  1272. value.
  1273. Returns:
  1274. URL: A new :class:`URL` instance with the parameter added.
  1275. """
  1276. return self.replace(query=self.query + ((name, value),))
  1277. def set(self, name, value=None):
  1278. """Make a new :class:`URL` instance with the query parameter *name*
  1279. set to *value*. All existing occurences, if any are replaced
  1280. by the single name-value pair.
  1281. >>> URL.from_text(u'https://example.com/?x=y').set(u'x')
  1282. URL.from_text(u'https://example.com/?x')
  1283. >>> URL.from_text(u'https://example.com/?x=y').set(u'x', u'z')
  1284. URL.from_text(u'https://example.com/?x=z')
  1285. Args:
  1286. name (unicode): The name of the query parameter to set. The
  1287. part before the ``=``.
  1288. value (unicode): The value of the query parameter to set. The
  1289. part after the ``=``. Defaults to ``None``, meaning no
  1290. value.
  1291. Returns:
  1292. URL: A new :class:`URL` instance with the parameter set.
  1293. """
  1294. # Preserve the original position of the query key in the list
  1295. q = [(k, v) for (k, v) in self.query if k != name]
  1296. idx = next((i for (i, (k, v)) in enumerate(self.query)
  1297. if k == name), -1)
  1298. q[idx:idx] = [(name, value)]
  1299. return self.replace(query=q)
  1300. def get(self, name):
  1301. """Get a list of values for the given query parameter, *name*::
  1302. >>> url = URL.from_text(u'?x=1&x=2')
  1303. >>> url.get('x')
  1304. [u'1', u'2']
  1305. >>> url.get('y')
  1306. []
  1307. If the given *name* is not set, an empty list is returned. A
  1308. list is always returned, and this method raises no exceptions.
  1309. Args:
  1310. name (unicode): The name of the query parameter to get.
  1311. Returns:
  1312. list: A list of all the values associated with the key, in
  1313. string form.
  1314. """
  1315. return [value for (key, value) in self.query if name == key]
  1316. def remove(self, name, value=_UNSET, limit=None):
  1317. """Make a new :class:`URL` instance with occurrences of the query
  1318. parameter *name* removed, or, if *value* is set, parameters
  1319. matching *name* and *value*. No exception is raised if the
  1320. parameter is not already set.
  1321. Args:
  1322. name (unicode): The name of the query parameter to remove.
  1323. value (unicode): Optional value to additionally filter
  1324. on. Setting this removes query parameters which match
  1325. both name and value.
  1326. limit (int): Optional maximum number of parameters to remove.
  1327. Returns:
  1328. URL: A new :class:`URL` instance with the parameter removed.
  1329. """
  1330. if limit is None:
  1331. if value is _UNSET:
  1332. nq = [(k, v) for (k, v) in self.query if k != name]
  1333. else:
  1334. nq = [(k, v) for (k, v) in self.query if not (k == name and v == value)]
  1335. else:
  1336. nq, removed_count = [], 0
  1337. for k, v in self.query:
  1338. if k == name and (value is _UNSET or v == value) and removed_count < limit:
  1339. removed_count += 1 # drop it
  1340. else:
  1341. nq.append((k, v)) # keep it
  1342. return self.replace(query=nq)
  1343. EncodedURL = URL # An alias better describing what the URL really is
  1344. class DecodedURL(object):
  1345. """DecodedURL is a type meant to act as a higher-level interface to
  1346. the URL. It is the `unicode` to URL's `bytes`. `DecodedURL` has
  1347. almost exactly the same API as `URL`, but everything going in and
  1348. out is in its maximally decoded state. All percent decoding is
  1349. handled automatically.
  1350. Where applicable, a UTF-8 encoding is presumed. Be advised that
  1351. some interactions can raise :exc:`UnicodeEncodeErrors` and
  1352. :exc:`UnicodeDecodeErrors`, just like when working with
  1353. bytestrings. Examples of such interactions include handling query
  1354. strings encoding binary data, and paths containing segments with
  1355. special characters encoded with codecs other than UTF-8.
  1356. Args:
  1357. url (URL): A :class:`URL` object to wrap.
  1358. lazy (bool): Set to True to avoid pre-decode all parts of the
  1359. URL to check for validity. Defaults to False.
  1360. """
  1361. def __init__(self, url, lazy=False):
  1362. self._url = url
  1363. if not lazy:
  1364. # cache the following, while triggering any decoding
  1365. # issues with decodable fields
  1366. self.host, self.userinfo, self.path, self.query, self.fragment
  1367. return
  1368. @classmethod
  1369. def from_text(cls, text, lazy=False):
  1370. """\
  1371. Make a `DecodedURL` instance from any text string containing a URL.
  1372. Args:
  1373. text (unicode): Text containing the URL
  1374. lazy (bool): Whether to pre-decode all parts of the URL to
  1375. check for validity. Defaults to True.
  1376. """
  1377. _url = URL.from_text(text)
  1378. return cls(_url, lazy=lazy)
  1379. @property
  1380. def encoded_url(self):
  1381. """Access the underlying :class:`URL` object, which has any special
  1382. characters encoded.
  1383. """
  1384. return self._url
  1385. def to_text(self, *a, **kw):
  1386. "Passthrough to :meth:`~hyperlink.URL.to_text()`"
  1387. return self._url.to_text(*a, **kw)
  1388. def to_uri(self, *a, **kw):
  1389. "Passthrough to :meth:`~hyperlink.URL.to_uri()`"
  1390. return self._url.to_uri(*a, **kw)
  1391. def to_iri(self, *a, **kw):
  1392. "Passthrough to :meth:`~hyperlink.URL.to_iri()`"
  1393. return self._url.to_iri(*a, **kw)
  1394. def click(self, href=u''):
  1395. "Return a new DecodedURL wrapping the result of :meth:`~hyperlink.URL.click()`"
  1396. if isinstance(href, DecodedURL):
  1397. href = href._url
  1398. return self.__class__(self._url.click(href=href))
  1399. def sibling(self, segment):
  1400. """Automatically encode any reserved characters in *segment* and
  1401. return a new `DecodedURL` wrapping the result of
  1402. :meth:`~hyperlink.URL.sibling()`
  1403. """
  1404. return self.__class__(self._url.sibling(_encode_reserved(segment)))
  1405. def child(self, *segments):
  1406. """Automatically encode any reserved characters in *segments* and
  1407. return a new `DecodedURL` wrapping the result of
  1408. :meth:`~hyperlink.URL.child()`.
  1409. """
  1410. if not segments:
  1411. return self
  1412. new_segs = [_encode_reserved(s) for s in segments]
  1413. return self.__class__(self._url.child(*new_segs))
  1414. def normalize(self, *a, **kw):
  1415. "Return a new `DecodedURL` wrapping the result of :meth:`~hyperlink.URL.normalize()`"
  1416. return self.__class__(self._url.normalize(*a, **kw))
  1417. @property
  1418. def absolute(self):
  1419. return self._url.absolute
  1420. @property
  1421. def scheme(self):
  1422. return self._url.scheme
  1423. @property
  1424. def host(self):
  1425. return _decode_host(self._url.host)
  1426. @property
  1427. def port(self):
  1428. return self._url.port
  1429. @property
  1430. def rooted(self):
  1431. return self._url.rooted
  1432. @property
  1433. def path(self):
  1434. try:
  1435. return self._path
  1436. except AttributeError:
  1437. pass
  1438. self._path = tuple([_percent_decode(p, raise_subencoding_exc=True)
  1439. for p in self._url.path])
  1440. return self._path
  1441. @property
  1442. def query(self):
  1443. try:
  1444. return self._query
  1445. except AttributeError:
  1446. pass
  1447. _q = [tuple(_percent_decode(x, raise_subencoding_exc=True)
  1448. if x is not None else None
  1449. for x in (k, v))
  1450. for k, v in self._url.query]
  1451. self._query = tuple(_q)
  1452. return self._query
  1453. @property
  1454. def fragment(self):
  1455. try:
  1456. return self._fragment
  1457. except AttributeError:
  1458. pass
  1459. frag = self._url.fragment
  1460. self._fragment = _percent_decode(frag, raise_subencoding_exc=True)
  1461. return self._fragment
  1462. @property
  1463. def userinfo(self):
  1464. try:
  1465. return self._userinfo
  1466. except AttributeError:
  1467. pass
  1468. self._userinfo = tuple([_percent_decode(p, raise_subencoding_exc=True)
  1469. for p in self._url.userinfo.split(':', 1)])
  1470. return self._userinfo
  1471. @property
  1472. def user(self):
  1473. return self.userinfo[0]
  1474. @property
  1475. def uses_netloc(self):
  1476. return self._url.uses_netloc
  1477. def replace(self, scheme=_UNSET, host=_UNSET, path=_UNSET, query=_UNSET,
  1478. fragment=_UNSET, port=_UNSET, rooted=_UNSET, userinfo=_UNSET,
  1479. uses_netloc=_UNSET):
  1480. """While the signature is the same, this `replace()` differs a little
  1481. from URL.replace. For instance, it accepts userinfo as a
  1482. tuple, not as a string, handling the case of having a username
  1483. containing a `:`. As with the rest of the methods on
  1484. DecodedURL, if you pass a reserved character, it will be
  1485. automatically encoded instead of an error being raised.
  1486. """
  1487. if path is not _UNSET:
  1488. path = [_encode_reserved(p) for p in path]
  1489. if query is not _UNSET:
  1490. query = [[_encode_reserved(x)
  1491. if x is not None else None
  1492. for x in (k, v)]
  1493. for k, v in iter_pairs(query)]
  1494. if userinfo is not _UNSET:
  1495. if len(userinfo) > 2:
  1496. raise ValueError('userinfo expected sequence of ["user"] or'
  1497. ' ["user", "password"], got %r' % userinfo)
  1498. userinfo = u':'.join([_encode_reserved(p) for p in userinfo])
  1499. new_url = self._url.replace(scheme=scheme,
  1500. host=host,
  1501. path=path,
  1502. query=query,
  1503. fragment=fragment,
  1504. port=port,
  1505. rooted=rooted,
  1506. userinfo=userinfo,
  1507. uses_netloc=uses_netloc)
  1508. return self.__class__(url=new_url)
  1509. def get(self, name):
  1510. "Get the value of all query parameters whose name matches *name*"
  1511. return [v for (k, v) in self.query if name == k]
  1512. def add(self, name, value=None):
  1513. "Return a new DecodedURL with the query parameter *name* and *value* added."
  1514. return self.replace(query=self.query + ((name, value),))
  1515. def set(self, name, value=None):
  1516. "Return a new DecodedURL with query parameter *name* set to *value*"
  1517. query = self.query
  1518. q = [(k, v) for (k, v) in query if k != name]
  1519. idx = next((i for (i, (k, v)) in enumerate(query) if k == name), -1)
  1520. q[idx:idx] = [(name, value)]
  1521. return self.replace(query=q)
  1522. def remove(self, name, value=_UNSET, limit=None):
  1523. """Return a new DecodedURL with query parameter *name* removed.
  1524. Optionally also filter for *value*, as well as cap the number
  1525. of parameters removed with *limit*.
  1526. """
  1527. if limit is None:
  1528. if value is _UNSET:
  1529. nq = [(k, v) for (k, v) in self.query if k != name]
  1530. else:
  1531. nq = [(k, v) for (k, v) in self.query if not (k == name and v == value)]
  1532. else:
  1533. nq, removed_count = [], 0
  1534. for k, v in self.query:
  1535. if k == name and (value is _UNSET or v == value) and removed_count < limit:
  1536. removed_count += 1 # drop it
  1537. else:
  1538. nq.append((k, v)) # keep it
  1539. return self.replace(query=nq)
  1540. def __repr__(self):
  1541. cn = self.__class__.__name__
  1542. return '%s(url=%r)' % (cn, self._url)
  1543. def __str__(self):
  1544. # TODO: the underlying URL's __str__ needs to change to make
  1545. # this work as the URL, see #55
  1546. return str(self._url)
  1547. def __eq__(self, other):
  1548. if not isinstance(other, self.__class__):
  1549. return NotImplemented
  1550. return self.normalize().to_uri() == other.normalize().to_uri()
  1551. def __ne__(self, other):
  1552. if not isinstance(other, self.__class__):
  1553. return NotImplemented
  1554. return not self.__eq__(other)
  1555. def __hash__(self):
  1556. return hash((self.__class__, self.scheme, self.userinfo, self.host,
  1557. self.path, self.query, self.fragment, self.port,
  1558. self.rooted, self.uses_netloc))
  1559. # # Begin Twisted Compat Code
  1560. asURI = to_uri
  1561. asIRI = to_iri
  1562. @classmethod
  1563. def fromText(cls, s, lazy=False):
  1564. return cls.from_text(s, lazy=lazy)
  1565. def asText(self, includeSecrets=False):
  1566. return self.to_text(with_password=includeSecrets)
  1567. def __dir__(self):
  1568. try:
  1569. ret = object.__dir__(self)
  1570. except AttributeError:
  1571. # object.__dir__ == AttributeError # pdw for py2
  1572. ret = dir(self.__class__) + list(self.__dict__.keys())
  1573. ret = sorted(set(ret) - set(['fromText', 'asURI', 'asIRI', 'asText']))
  1574. return ret
  1575. # # End Twisted Compat Code
  1576. def parse(url, decoded=True, lazy=False):
  1577. """Automatically turn text into a structured URL object.
  1578. Args:
  1579. decoded (bool): Whether or not to return a :class:`DecodedURL`,
  1580. which automatically handles all
  1581. encoding/decoding/quoting/unquoting for all the various
  1582. accessors of parts of the URL, or an :class:`EncodedURL`,
  1583. which has the same API, but requires handling of special
  1584. characters for different parts of the URL.
  1585. lazy (bool): In the case of `decoded=True`, this controls
  1586. whether the URL is decoded immediately or as accessed. The
  1587. default, `lazy=False`, checks all encoded parts of the URL
  1588. for decodability.
  1589. """
  1590. enc_url = EncodedURL.from_text(url)
  1591. if not decoded:
  1592. return enc_url
  1593. dec_url = DecodedURL(enc_url, lazy=lazy)
  1594. return dec_url