Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 82KB

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