urlutils.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, Mahmoud Hashemi
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. #
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following
  13. # disclaimer in the documentation and/or other materials provided
  14. # with the distribution.
  15. #
  16. # * The names of the contributors may not be used to endorse or
  17. # promote products derived from this software without specific
  18. # prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """:mod:`urlutils` is a module dedicated to one of software's most
  32. versatile, well-aged, and beloved data structures: the URL, also known
  33. as the `Uniform Resource Locator`_.
  34. Among other things, this module is a full reimplementation of URLs,
  35. without any reliance on the :mod:`urlparse` or :mod:`urllib` standard
  36. library modules. The centerpiece and top-level interface of urlutils
  37. is the :class:`URL` type. Also featured is the :func:`find_all_links`
  38. convenience function. Some low-level functions and constants are also
  39. below.
  40. The implementations in this module are based heavily on `RFC 3986`_ and
  41. `RFC 3987`_, and incorporates details from several other RFCs and `W3C
  42. documents`_.
  43. .. _Uniform Resource Locator: https://en.wikipedia.org/wiki/Uniform_Resource_Locator
  44. .. _RFC 3986: https://tools.ietf.org/html/rfc3986
  45. .. _RFC 3987: https://tools.ietf.org/html/rfc3987
  46. .. _W3C documents: https://www.w3.org/TR/uri-clarification/
  47. """
  48. import re
  49. import socket
  50. import string
  51. from unicodedata import normalize
  52. unicode = type(u'')
  53. try:
  54. unichr
  55. except NameError:
  56. unichr = chr
  57. # The unreserved URI characters (per RFC 3986 Section 2.3)
  58. _UNRESERVED_CHARS = frozenset('~-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  59. 'abcdefghijklmnopqrstuvwxyz')
  60. # URL parsing regex (based on RFC 3986 Appendix B, with modifications)
  61. _URL_RE = re.compile(r'^((?P<scheme>[^:/?#]+):)?'
  62. r'((?P<_netloc_sep>//)(?P<authority>[^/?#]*))?'
  63. r'(?P<path>[^?#]*)'
  64. r'(\?(?P<query>[^#]*))?'
  65. r'(#(?P<fragment>.*))?')
  66. _HEX_CHAR_MAP = dict([((a + b).encode('ascii'),
  67. unichr(int(a + b, 16)).encode('charmap'))
  68. for a in string.hexdigits for b in string.hexdigits])
  69. _ASCII_RE = re.compile('([\x00-\x7f]+)')
  70. # This port list painstakingly curated by hand searching through
  71. # https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
  72. # and
  73. # https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
  74. SCHEME_PORT_MAP = {'acap': 674, 'afp': 548, 'dict': 2628, 'dns': 53,
  75. 'file': None, 'ftp': 21, 'git': 9418, 'gopher': 70,
  76. 'http': 80, 'https': 443, 'imap': 143, 'ipp': 631,
  77. 'ipps': 631, 'irc': 194, 'ircs': 6697, 'ldap': 389,
  78. 'ldaps': 636, 'mms': 1755, 'msrp': 2855, 'msrps': None,
  79. 'mtqp': 1038, 'nfs': 111, 'nntp': 119, 'nntps': 563,
  80. 'pop': 110, 'prospero': 1525, 'redis': 6379, 'rsync': 873,
  81. 'rtsp': 554, 'rtsps': 322, 'rtspu': 5005, 'sftp': 22,
  82. 'smb': 445, 'snmp': 161, 'ssh': 22, 'steam': None,
  83. 'svn': 3690, 'telnet': 23, 'ventrilo': 3784, 'vnc': 5900,
  84. 'wais': 210, 'ws': 80, 'wss': 443, 'xmpp': None}
  85. # This list of schemes that don't use authorities is also from the link above.
  86. NO_NETLOC_SCHEMES = set(['urn', 'about', 'bitcoin', 'blob', 'data', 'geo',
  87. 'magnet', 'mailto', 'news', 'pkcs11',
  88. 'sip', 'sips', 'tel'])
  89. # As of Mar 11, 2017, there were 44 netloc schemes, and 13 non-netloc
  90. # RFC 3986 section 2.2, Reserved Characters
  91. _GEN_DELIMS = frozenset(u':/?#[]@')
  92. _SUB_DELIMS = frozenset(u"!$&'()*+,;=")
  93. _ALL_DELIMS = _GEN_DELIMS | _SUB_DELIMS
  94. _USERINFO_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS
  95. _USERINFO_DELIMS = _ALL_DELIMS - _USERINFO_SAFE
  96. _PATH_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS | set(u':@')
  97. _PATH_DELIMS = _ALL_DELIMS - _PATH_SAFE
  98. _FRAGMENT_SAFE = _UNRESERVED_CHARS | _PATH_SAFE | set(u'/?')
  99. _FRAGMENT_DELIMS = _ALL_DELIMS - _FRAGMENT_SAFE
  100. _QUERY_SAFE = _UNRESERVED_CHARS | _FRAGMENT_SAFE - set(u'&=+')
  101. _QUERY_DELIMS = _ALL_DELIMS - _QUERY_SAFE
  102. class URLParseError(ValueError):
  103. """Exception inheriting from :exc:`ValueError`, raised when failing to
  104. parse a URL. Mostly raised on invalid ports and IPv6 addresses.
  105. """
  106. pass
  107. DEFAULT_ENCODING = 'utf8'
  108. def to_unicode(obj):
  109. try:
  110. return unicode(obj)
  111. except UnicodeDecodeError:
  112. return unicode(obj, encoding=DEFAULT_ENCODING)
  113. # regex from gruber via tornado
  114. # doesn't support ipv6
  115. # doesn't support mailto (netloc-less schemes)
  116. _FIND_ALL_URL_RE = re.compile(to_unicode(r"""\b((?:([\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\s&()<>]|&amp;|&quot;)*(?:[^!"#$%'()*+,.:;<=>?@\[\]^`{|}~\s]))|(?:\((?:[^\s&()]|&amp;|&quot;)*\)))+)"""))
  117. def find_all_links(text, with_text=False, default_scheme='https', schemes=()):
  118. """This function uses heuristics to searches plain text for strings
  119. that look like URLs, returning a :class:`list` of :class:`URL`
  120. objects. It supports limiting the accepted schemes, and returning
  121. interleaved text as well.
  122. >>> find_all_links('Visit https://boltons.rtfd.org!')
  123. [URL(u'https://boltons.rtfd.org')]
  124. >>> find_all_links('Visit https://boltons.rtfd.org!', with_text=True)
  125. [u'Visit ', URL(u'https://boltons.rtfd.org'), u'!']
  126. Args:
  127. text (str): The text to search.
  128. with_text (bool): Whether or not to interleave plaintext blocks
  129. with the returned URL objects. Having all tokens can be
  130. useful for transforming the text, e.g., replacing links with
  131. HTML equivalents. Defaults to ``False``.
  132. default_scheme (str): Many URLs are written without the scheme
  133. component. This function can match a reasonable subset of
  134. those, provided *default_scheme* is set to a string. Set to
  135. ``False`` to disable matching scheme-less URLs. Defaults to
  136. ``'https'``.
  137. schemes (list): A list of strings that a URL's scheme must
  138. match in order to be included in the results. Defaults to
  139. empty, which matches all schemes.
  140. .. note:: Currently this function does not support finding IPv6
  141. addresses or URLs with netloc-less schemes, like mailto.
  142. """
  143. text = to_unicode(text)
  144. prev_end, start, end = 0, None, None
  145. ret = []
  146. _add = ret.append
  147. def _add_text(t):
  148. if ret and isinstance(ret[-1], unicode):
  149. ret[-1] += t
  150. else:
  151. _add(t)
  152. for match in _FIND_ALL_URL_RE.finditer(text):
  153. start, end = match.start(1), match.end(1)
  154. if prev_end < start and with_text:
  155. _add(text[prev_end:start])
  156. prev_end = end
  157. try:
  158. cur_url_text = match.group(0)
  159. cur_url = URL(cur_url_text)
  160. if not cur_url.scheme:
  161. if default_scheme:
  162. cur_url = URL(default_scheme + '://' + cur_url_text)
  163. else:
  164. _add_text(text[start:end])
  165. continue
  166. if schemes and cur_url.scheme not in schemes:
  167. _add_text(text[start:end])
  168. else:
  169. _add(cur_url)
  170. except URLParseError:
  171. # currently this should only be hit with broken port
  172. # strings. the regex above doesn't support ipv6 addresses
  173. if with_text:
  174. _add_text(text[start:end])
  175. if with_text:
  176. tail = text[prev_end:]
  177. if tail:
  178. _add_text(tail)
  179. return ret
  180. def _make_quote_map(safe_chars):
  181. ret = {}
  182. # v is included in the dict for py3 mostly, because bytestrings
  183. # are iterables of ints, of course!
  184. for i, v in zip(range(256), range(256)):
  185. c = chr(v)
  186. if c in safe_chars:
  187. ret[c] = ret[v] = c
  188. else:
  189. ret[c] = ret[v] = '%{0:02X}'.format(i)
  190. return ret
  191. _USERINFO_PART_QUOTE_MAP = _make_quote_map(_USERINFO_SAFE)
  192. _PATH_PART_QUOTE_MAP = _make_quote_map(_PATH_SAFE)
  193. _QUERY_PART_QUOTE_MAP = _make_quote_map(_QUERY_SAFE)
  194. _FRAGMENT_QUOTE_MAP = _make_quote_map(_FRAGMENT_SAFE)
  195. def quote_path_part(text, full_quote=True):
  196. """
  197. Percent-encode a single segment of a URL path.
  198. """
  199. if full_quote:
  200. bytestr = normalize('NFC', to_unicode(text)).encode('utf8')
  201. return u''.join([_PATH_PART_QUOTE_MAP[b] for b in bytestr])
  202. return u''.join([_PATH_PART_QUOTE_MAP[t] if t in _PATH_DELIMS else t
  203. for t in text])
  204. def quote_query_part(text, full_quote=True):
  205. """
  206. Percent-encode a single query string key or value.
  207. """
  208. if full_quote:
  209. bytestr = normalize('NFC', to_unicode(text)).encode('utf8')
  210. return u''.join([_QUERY_PART_QUOTE_MAP[b] for b in bytestr])
  211. return u''.join([_QUERY_PART_QUOTE_MAP[t] if t in _QUERY_DELIMS else t
  212. for t in text])
  213. def quote_fragment_part(text, full_quote=True):
  214. """Quote the fragment part of the URL. Fragments don't have
  215. subdelimiters, so the whole URL fragment can be passed.
  216. """
  217. if full_quote:
  218. bytestr = normalize('NFC', to_unicode(text)).encode('utf8')
  219. return u''.join([_FRAGMENT_QUOTE_MAP[b] for b in bytestr])
  220. return u''.join([_FRAGMENT_QUOTE_MAP[t] if t in _FRAGMENT_DELIMS else t
  221. for t in text])
  222. def quote_userinfo_part(text, full_quote=True):
  223. """Quote special characters in either the username or password
  224. section of the URL. Note that userinfo in URLs is considered
  225. deprecated in many circles (especially browsers), and support for
  226. percent-encoded userinfo can be spotty.
  227. """
  228. if full_quote:
  229. bytestr = normalize('NFC', to_unicode(text)).encode('utf8')
  230. return u''.join([_USERINFO_PART_QUOTE_MAP[b] for b in bytestr])
  231. return u''.join([_USERINFO_PART_QUOTE_MAP[t] if t in _USERINFO_DELIMS
  232. else t for t in text])
  233. def unquote(string, encoding='utf-8', errors='replace'):
  234. """Percent-decode a string, by replacing %xx escapes with their
  235. single-character equivalent. The optional *encoding* and *errors*
  236. parameters specify how to decode percent-encoded sequences into
  237. Unicode characters, as accepted by the :meth:`bytes.decode()` method. By
  238. default, percent-encoded sequences are decoded with UTF-8, and
  239. invalid sequences are replaced by a placeholder character.
  240. >>> unquote(u'abc%20def')
  241. u'abc def'
  242. """
  243. if '%' not in string:
  244. string.split
  245. return string
  246. if encoding is None:
  247. encoding = 'utf-8'
  248. if errors is None:
  249. errors = 'replace'
  250. bits = _ASCII_RE.split(string)
  251. res = [bits[0]]
  252. append = res.append
  253. for i in range(1, len(bits), 2):
  254. append(unquote_to_bytes(bits[i]).decode(encoding, errors))
  255. append(bits[i + 1])
  256. return ''.join(res)
  257. def unquote_to_bytes(string):
  258. """unquote_to_bytes('abc%20def') -> b'abc def'."""
  259. # Note: strings are encoded as UTF-8. This is only an issue if it contains
  260. # unescaped non-ASCII characters, which URIs should not.
  261. if not string:
  262. # Is it a string-like object?
  263. string.split
  264. return b''
  265. if isinstance(string, unicode):
  266. string = string.encode('utf-8')
  267. bits = string.split(b'%')
  268. if len(bits) == 1:
  269. return string
  270. # import pdb;pdb.set_trace()
  271. res = [bits[0]]
  272. append = res.append
  273. for item in bits[1:]:
  274. try:
  275. append(_HEX_CHAR_MAP[item[:2]])
  276. append(item[2:])
  277. except KeyError:
  278. append(b'%')
  279. append(item)
  280. return b''.join(res)
  281. def register_scheme(text, uses_netloc=None, default_port=None):
  282. """Registers new scheme information, resulting in correct port and
  283. slash behavior from the URL object. There are dozens of standard
  284. schemes preregistered, so this function is mostly meant for
  285. proprietary internal customizations or stopgaps on missing
  286. standards information. If a scheme seems to be missing, please
  287. `file an issue`_!
  288. Args:
  289. text (str): Text representing the scheme.
  290. (the 'http' in 'http://hatnote.com')
  291. uses_netloc (bool): Does the scheme support specifying a
  292. network host? For instance, "http" does, "mailto" does not.
  293. default_port (int): The default port, if any, for netloc-using
  294. schemes.
  295. .. _file an issue: https://github.com/mahmoud/boltons/issues
  296. """
  297. text = text.lower()
  298. if default_port is not None:
  299. try:
  300. default_port = int(default_port)
  301. except ValueError:
  302. raise ValueError('default_port expected integer or None, not %r'
  303. % (default_port,))
  304. if uses_netloc is True:
  305. SCHEME_PORT_MAP[text] = default_port
  306. elif uses_netloc is False:
  307. if default_port is not None:
  308. raise ValueError('unexpected default port while specifying'
  309. ' non-netloc scheme: %r' % default_port)
  310. NO_NETLOC_SCHEMES.add(text)
  311. elif uses_netloc is not None:
  312. raise ValueError('uses_netloc expected True, False, or None')
  313. return
  314. def resolve_path_parts(path_parts):
  315. """Normalize the URL path by resolving segments of '.' and '..',
  316. resulting in a dot-free path. See RFC 3986 section 5.2.4, Remove
  317. Dot Segments.
  318. """
  319. # TODO: what to do with multiple slashes
  320. ret = []
  321. for part in path_parts:
  322. if part == u'.':
  323. pass
  324. elif part == u'..':
  325. if ret and (len(ret) > 1 or ret[0]): # prevent unrooting
  326. ret.pop()
  327. else:
  328. ret.append(part)
  329. if list(path_parts[-1:]) in ([u'.'], [u'..']):
  330. ret.append(u'')
  331. return ret
  332. class cachedproperty(object):
  333. """The ``cachedproperty`` is used similar to :class:`property`, except
  334. that the wrapped method is only called once. This is commonly used
  335. to implement lazy attributes.
  336. After the property has been accessed, the value is stored on the
  337. instance itself, using the same name as the cachedproperty. This
  338. allows the cache to be cleared with :func:`delattr`, or through
  339. manipulating the object's ``__dict__``.
  340. """
  341. def __init__(self, func):
  342. self.__doc__ = getattr(func, '__doc__')
  343. self.func = func
  344. def __get__(self, obj, objtype=None):
  345. if obj is None:
  346. return self
  347. value = obj.__dict__[self.func.__name__] = self.func(obj)
  348. return value
  349. def __repr__(self):
  350. cn = self.__class__.__name__
  351. return '<%s func=%s>' % (cn, self.func)
  352. class URL(object):
  353. r"""The URL is one of the most ubiquitous data structures in the
  354. virtual and physical landscape. From blogs to billboards, URLs are
  355. so common, that it's easy to overlook their complexity and
  356. power.
  357. There are 8 parts of a URL, each with its own semantics and
  358. special characters:
  359. * :attr:`~URL.scheme`
  360. * :attr:`~URL.username`
  361. * :attr:`~URL.password`
  362. * :attr:`~URL.host`
  363. * :attr:`~URL.port`
  364. * :attr:`~URL.path`
  365. * :attr:`~URL.query_params` (query string parameters)
  366. * :attr:`~URL.fragment`
  367. Each is exposed as an attribute on the URL object. RFC 3986 offers
  368. this brief structural summary of the main URL components::
  369. foo://user:pass@example.com:8042/over/there?name=ferret#nose
  370. \_/ \_______/ \_________/ \__/\_________/ \_________/ \__/
  371. | | | | | | |
  372. scheme userinfo host port path query fragment
  373. And here's how that example can be manipulated with the URL type:
  374. >>> url = URL('foo://example.com:8042/over/there?name=ferret#nose')
  375. >>> print(url.host)
  376. example.com
  377. >>> print(url.get_authority())
  378. example.com:8042
  379. >>> print(url.qp['name']) # qp is a synonym for query_params
  380. ferret
  381. URL's approach to encoding is that inputs are decoded as much as
  382. possible, and data remains in this decoded state until re-encoded
  383. using the :meth:`~URL.to_text()` method. In this way, it's similar
  384. to Python's current approach of encouraging immediate decoding of
  385. bytes to text.
  386. Note that URL instances are mutable objects. If an immutable
  387. representation of the URL is desired, the string from
  388. :meth:`~URL.to_text()` may be used. For an immutable, but
  389. almost-as-featureful, URL object, check out the `hyperlink
  390. package`_.
  391. .. _hyperlink package: https://github.com/mahmoud/hyperlink
  392. """
  393. # public attributes (for comparison, see __eq__):
  394. _cmp_attrs = ('scheme', 'uses_netloc', 'username', 'password',
  395. 'family', 'host', 'port', 'path', 'query_params', 'fragment')
  396. def __init__(self, url=''):
  397. # TODO: encoding param. The encoding that underlies the
  398. # percent-encoding is always utf8 for IRIs, but can be Latin-1
  399. # for other usage schemes.
  400. ud = DEFAULT_PARSED_URL
  401. if url:
  402. if isinstance(url, URL):
  403. url = url.to_text() # better way to copy URLs?
  404. elif isinstance(url, bytes):
  405. try:
  406. url = url.decode(DEFAULT_ENCODING)
  407. except UnicodeDecodeError as ude:
  408. raise URLParseError('expected text or %s-encoded bytes.'
  409. ' try decoding the url bytes and'
  410. ' passing the result. (got: %s)'
  411. % (DEFAULT_ENCODING, ude))
  412. ud = parse_url(url)
  413. _e = u''
  414. self.scheme = ud['scheme'] or _e
  415. self._netloc_sep = ud['_netloc_sep'] or _e
  416. self.username = (unquote(ud['username'])
  417. if '%' in (ud['username'] or _e) else ud['username'] or _e)
  418. self.password = (unquote(ud['password'])
  419. if '%' in (ud['password'] or _e) else ud['password'] or _e)
  420. self.family = ud['family']
  421. if not ud['host']:
  422. self.host = _e
  423. else:
  424. try:
  425. self.host = ud['host'].encode("ascii")
  426. except UnicodeEncodeError:
  427. self.host = ud['host'] # already non-ascii text
  428. else:
  429. self.host = self.host.decode("idna")
  430. self.port = ud['port']
  431. self.path_parts = tuple([unquote(p) if '%' in p else p for p
  432. in (ud['path'] or _e).split(u'/')])
  433. self._query = ud['query'] or _e
  434. self.fragment = (unquote(ud['fragment'])
  435. if '%' in (ud['fragment'] or _e) else ud['fragment'] or _e)
  436. # TODO: possibly use None as marker for empty vs missing
  437. return
  438. @classmethod
  439. def from_parts(cls, scheme=None, host=None, path_parts=(), query_params=(),
  440. fragment=u'', port=None, username=None, password=None):
  441. """Build a new URL from parts. Note that the respective arguments are
  442. not in the order they would appear in a URL:
  443. Args:
  444. scheme (str): The scheme of a URL, e.g., 'http'
  445. host (str): The host string, e.g., 'hatnote.com'
  446. path_parts (tuple): The individual text segments of the
  447. path, e.g., ('post', '123')
  448. query_params (dict): An OMD, dict, or list of (key, value)
  449. pairs representing the keys and values of the URL's query
  450. parameters.
  451. fragment (str): The fragment of the URL, e.g., 'anchor1'
  452. port (int): The integer port of URL, automatic defaults are
  453. available for registered schemes.
  454. username (str): The username for the userinfo part of the URL.
  455. password (str): The password for the userinfo part of the URL.
  456. Note that this method does relatively little
  457. validation. :meth:`URL.to_text()` should be used to check if
  458. any errors are produced while composing the final textual URL.
  459. """
  460. ret = cls()
  461. ret.scheme = scheme
  462. ret.host = host
  463. ret.path_parts = tuple(path_parts) or (u'',)
  464. ret.query_params.update(query_params)
  465. ret.fragment = fragment
  466. ret.port = port
  467. ret.username = username
  468. ret.password = password
  469. return ret
  470. @cachedproperty
  471. def query_params(self):
  472. """The parsed form of the query string of the URL, represented as a
  473. :class:`~dictutils.OrderedMultiDict`. Also available as the
  474. handy alias ``qp``.
  475. >>> url = URL('http://boltons.readthedocs.io/?utm_source=doctest&python=great')
  476. >>> url.qp.keys()
  477. [u'utm_source', u'python']
  478. """
  479. return QueryParamDict.from_text(self._query)
  480. qp = query_params
  481. @property
  482. def path(self):
  483. "The URL's path, in text form."
  484. return u'/'.join([quote_path_part(p, full_quote=False)
  485. for p in self.path_parts])
  486. @path.setter
  487. def path(self, path_text):
  488. self.path_parts = tuple([unquote(p) if '%' in p else p
  489. for p in to_unicode(path_text).split(u'/')])
  490. return
  491. @property
  492. def uses_netloc(self):
  493. """Whether or not a URL uses :code:`:` or :code:`://` to separate the
  494. scheme from the rest of the URL depends on the scheme's own
  495. standard definition. There is no way to infer this behavior
  496. from other parts of the URL. A scheme either supports network
  497. locations or it does not.
  498. The URL type's approach to this is to check for explicitly
  499. registered schemes, with common schemes like HTTP
  500. preregistered. This is the same approach taken by
  501. :mod:`urlparse`.
  502. URL adds two additional heuristics if the scheme as a whole is
  503. not registered. First, it attempts to check the subpart of the
  504. scheme after the last ``+`` character. This adds intuitive
  505. behavior for schemes like ``git+ssh``. Second, if a URL with
  506. an unrecognized scheme is loaded, it will maintain the
  507. separator it sees.
  508. >>> print(URL('fakescheme://test.com').to_text())
  509. fakescheme://test.com
  510. >>> print(URL('mockscheme:hello:world').to_text())
  511. mockscheme:hello:world
  512. """
  513. default = self._netloc_sep
  514. if self.scheme in SCHEME_PORT_MAP:
  515. return True
  516. if self.scheme in NO_NETLOC_SCHEMES:
  517. return False
  518. if self.scheme.split('+')[-1] in SCHEME_PORT_MAP:
  519. return True
  520. return default
  521. @property
  522. def default_port(self):
  523. """Return the default port for the currently-set scheme. Returns
  524. ``None`` if the scheme is unrecognized. See
  525. :func:`register_scheme` above. If :attr:`~URL.port` matches
  526. this value, no port is emitted in the output of
  527. :meth:`~URL.to_text()`.
  528. Applies the same '+' heuristic detailed in :meth:`URL.uses_netloc`.
  529. """
  530. try:
  531. return SCHEME_PORT_MAP[self.scheme]
  532. except KeyError:
  533. return SCHEME_PORT_MAP.get(self.scheme.split('+')[-1])
  534. def normalize(self, with_case=True):
  535. """Resolve any "." and ".." references in the path, as well as
  536. normalize scheme and host casing. To turn off case
  537. normalization, pass ``with_case=False``.
  538. More information can be found in `Section 6.2.2 of RFC 3986`_.
  539. .. _Section 6.2.2 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-6.2.2
  540. """
  541. self.path_parts = resolve_path_parts(self.path_parts)
  542. if with_case:
  543. self.scheme = self.scheme.lower()
  544. self.host = self.host.lower()
  545. return
  546. def navigate(self, dest):
  547. """Factory method that returns a _new_ :class:`URL` based on a given
  548. destination, *dest*. Useful for navigating those relative
  549. links with ease.
  550. The newly created :class:`URL` is normalized before being returned.
  551. >>> url = URL('http://boltons.readthedocs.io')
  552. >>> url.navigate('en/latest/')
  553. URL(u'http://boltons.readthedocs.io/en/latest/')
  554. Args:
  555. dest (str): A string or URL object representing the destination
  556. More information can be found in `Section 5 of RFC 3986`_.
  557. .. _Section 5 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-5
  558. """
  559. orig_dest = None
  560. if not isinstance(dest, URL):
  561. dest, orig_dest = URL(dest), dest
  562. if dest.scheme and dest.host:
  563. # absolute URLs replace everything, but don't make an
  564. # extra copy if we don't have to
  565. return URL(dest) if orig_dest is None else dest
  566. query_params = dest.query_params
  567. if dest.path:
  568. if dest.path.startswith(u'/'): # absolute path
  569. new_path_parts = list(dest.path_parts)
  570. else: # relative path
  571. new_path_parts = list(self.path_parts[:-1]) \
  572. + list(dest.path_parts)
  573. else:
  574. new_path_parts = list(self.path_parts)
  575. if not query_params:
  576. query_params = self.query_params
  577. ret = self.from_parts(scheme=dest.scheme or self.scheme,
  578. host=dest.host or self.host,
  579. port=dest.port or self.port,
  580. path_parts=new_path_parts,
  581. query_params=query_params,
  582. fragment=dest.fragment,
  583. username=dest.username or self.username,
  584. password=dest.password or self.password)
  585. ret.normalize()
  586. return ret
  587. def get_authority(self, full_quote=False, with_userinfo=False):
  588. """Used by URL schemes that have a network location,
  589. :meth:`~URL.get_authority` combines :attr:`username`,
  590. :attr:`password`, :attr:`host`, and :attr:`port` into one
  591. string, the *authority*, that is used for
  592. connecting to a network-accessible resource.
  593. Used internally by :meth:`~URL.to_text()` and can be useful
  594. for labeling connections.
  595. >>> url = URL('ftp://user@ftp.debian.org:2121/debian/README')
  596. >>> print(url.get_authority())
  597. ftp.debian.org:2121
  598. >>> print(url.get_authority(with_userinfo=True))
  599. user@ftp.debian.org:2121
  600. Args:
  601. full_quote (bool): Whether or not to apply IDNA encoding.
  602. Defaults to ``False``.
  603. with_userinfo (bool): Whether or not to include username
  604. and password, technically part of the
  605. authority. Defaults to ``False``.
  606. """
  607. parts = []
  608. _add = parts.append
  609. if self.username and with_userinfo:
  610. _add(quote_userinfo_part(self.username))
  611. if self.password:
  612. _add(':')
  613. _add(quote_userinfo_part(self.password))
  614. _add('@')
  615. if self.host:
  616. if self.family == socket.AF_INET6:
  617. _add('[')
  618. _add(self.host)
  619. _add(']')
  620. elif full_quote:
  621. _add(self.host.encode('idna').decode('ascii'))
  622. else:
  623. _add(self.host)
  624. # TODO: 0 port?
  625. if self.port and self.port != self.default_port:
  626. _add(':')
  627. _add(unicode(self.port))
  628. return u''.join(parts)
  629. def to_text(self, full_quote=False):
  630. """Render a string representing the current state of the URL
  631. object.
  632. >>> url = URL('http://listen.hatnote.com')
  633. >>> url.fragment = 'en'
  634. >>> print(url.to_text())
  635. http://listen.hatnote.com#en
  636. By setting the *full_quote* flag, the URL can either be fully
  637. quoted or minimally quoted. The most common characteristic of
  638. an encoded-URL is the presence of percent-encoded text (e.g.,
  639. %60). Unquoted URLs are more readable and suitable
  640. for display, whereas fully-quoted URLs are more conservative
  641. and generally necessary for sending over the network.
  642. """
  643. scheme = self.scheme
  644. path = u'/'.join([quote_path_part(p, full_quote=full_quote)
  645. for p in self.path_parts])
  646. authority = self.get_authority(full_quote=full_quote,
  647. with_userinfo=True)
  648. query_string = self.query_params.to_text(full_quote=full_quote)
  649. fragment = quote_fragment_part(self.fragment, full_quote=full_quote)
  650. parts = []
  651. _add = parts.append
  652. if scheme:
  653. _add(scheme)
  654. _add(':')
  655. if authority:
  656. _add('//')
  657. _add(authority)
  658. elif (scheme and path[:2] != '//' and self.uses_netloc):
  659. _add('//')
  660. if path:
  661. if scheme and authority and path[:1] != '/':
  662. _add('/')
  663. # TODO: i think this is here because relative paths
  664. # with absolute authorities = undefined
  665. _add(path)
  666. if query_string:
  667. _add('?')
  668. _add(query_string)
  669. if fragment:
  670. _add('#')
  671. _add(fragment)
  672. return u''.join(parts)
  673. def __repr__(self):
  674. cn = self.__class__.__name__
  675. return u'%s(%r)' % (cn, self.to_text())
  676. def __str__(self):
  677. return self.to_text()
  678. def __unicode__(self):
  679. return self.to_text()
  680. def __eq__(self, other):
  681. for attr in self._cmp_attrs:
  682. if not getattr(self, attr) == getattr(other, attr, None):
  683. return False
  684. return True
  685. def __ne__(self, other):
  686. return not self == other
  687. try:
  688. from socket import inet_pton
  689. except ImportError:
  690. # from https://gist.github.com/nnemkin/4966028
  691. import ctypes
  692. class _sockaddr(ctypes.Structure):
  693. _fields_ = [("sa_family", ctypes.c_short),
  694. ("__pad1", ctypes.c_ushort),
  695. ("ipv4_addr", ctypes.c_byte * 4),
  696. ("ipv6_addr", ctypes.c_byte * 16),
  697. ("__pad2", ctypes.c_ulong)]
  698. WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA
  699. WSAAddressToStringA = ctypes.windll.ws2_32.WSAAddressToStringA
  700. def inet_pton(address_family, ip_string):
  701. addr = _sockaddr()
  702. ip_string = ip_string.encode('ascii')
  703. addr.sa_family = address_family
  704. addr_size = ctypes.c_int(ctypes.sizeof(addr))
  705. if WSAStringToAddressA(ip_string, address_family, None, ctypes.byref(addr), ctypes.byref(addr_size)) != 0:
  706. raise socket.error(ctypes.FormatError())
  707. if address_family == socket.AF_INET:
  708. return ctypes.string_at(addr.ipv4_addr, 4)
  709. if address_family == socket.AF_INET6:
  710. return ctypes.string_at(addr.ipv6_addr, 16)
  711. raise socket.error('unknown address family')
  712. def parse_host(host):
  713. """\
  714. Low-level function used to parse the host portion of a URL.
  715. Returns a tuple of (family, host) where *family* is a
  716. :mod:`socket` module constant or ``None``, and host is a string.
  717. >>> parse_host('googlewebsite.com') == (None, 'googlewebsite.com')
  718. True
  719. >>> parse_host('[::1]') == (socket.AF_INET6, '::1')
  720. True
  721. >>> parse_host('192.168.1.1') == (socket.AF_INET, '192.168.1.1')
  722. True
  723. Odd doctest formatting above due to py3's switch from int to enums
  724. for :mod:`socket` constants.
  725. """
  726. if not host:
  727. return None, u''
  728. if u':' in host and u'[' == host[0] and u']' == host[-1]:
  729. host = host[1:-1]
  730. try:
  731. inet_pton(socket.AF_INET6, host)
  732. except socket.error as se:
  733. raise URLParseError('invalid IPv6 host: %r (%r)' % (host, se))
  734. except UnicodeEncodeError:
  735. pass # TODO: this can't be a real host right?
  736. else:
  737. family = socket.AF_INET6
  738. return family, host
  739. try:
  740. inet_pton(socket.AF_INET, host)
  741. except (socket.error, UnicodeEncodeError):
  742. family = None # not an IP
  743. else:
  744. family = socket.AF_INET
  745. return family, host
  746. def parse_url(url_text):
  747. """\
  748. Used to parse the text for a single URL into a dictionary, used
  749. internally by the :class:`URL` type.
  750. Note that "URL" has a very narrow, standards-based
  751. definition. While :func:`parse_url` may raise
  752. :class:`URLParseError` under a very limited number of conditions,
  753. such as non-integer port, a surprising number of strings are
  754. technically valid URLs. For instance, the text ``"url"`` is a
  755. valid URL, because it is a relative path.
  756. In short, do not expect this function to validate form inputs or
  757. other more colloquial usages of URLs.
  758. >>> res = parse_url('http://127.0.0.1:3000/?a=1')
  759. >>> sorted(res.keys()) # res is a basic dictionary
  760. ['_netloc_sep', 'authority', 'family', 'fragment', 'host', 'password', 'path', 'port', 'query', 'scheme', 'username']
  761. """
  762. url_text = unicode(url_text)
  763. # raise TypeError('parse_url expected text, not %r' % url_str)
  764. um = _URL_RE.match(url_text)
  765. try:
  766. gs = um.groupdict()
  767. except AttributeError:
  768. raise URLParseError('could not parse url: %r' % url_text)
  769. au_text = gs['authority']
  770. user, pw, hostinfo = None, None, au_text
  771. if au_text:
  772. userinfo, sep, hostinfo = au_text.rpartition('@')
  773. if sep:
  774. # TODO: empty userinfo error?
  775. user, _, pw = userinfo.partition(':')
  776. host, port = None, None
  777. if hostinfo:
  778. host, sep, port_str = hostinfo.partition(u':')
  779. if sep:
  780. if host and host[0] == u'[' and u']' in port_str:
  781. host_right, _, port_str = port_str.partition(u']')
  782. host = host + u':' + host_right + u']'
  783. if port_str and port_str[0] == u':':
  784. port_str = port_str[1:]
  785. try:
  786. port = int(port_str)
  787. except ValueError:
  788. if port_str: # empty ports ok according to RFC 3986 6.2.3
  789. raise URLParseError('expected integer for port, not %r'
  790. % port_str)
  791. port = None
  792. family, host = parse_host(host)
  793. gs['username'] = user
  794. gs['password'] = pw
  795. gs['family'] = family
  796. gs['host'] = host
  797. gs['port'] = port
  798. return gs
  799. DEFAULT_PARSED_URL = parse_url('')
  800. def parse_qsl(qs, keep_blank_values=True, encoding=DEFAULT_ENCODING):
  801. """
  802. Converts a query string into a list of (key, value) pairs.
  803. """
  804. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  805. ret = []
  806. for pair in pairs:
  807. if not pair:
  808. continue
  809. key, _, value = pair.partition('=')
  810. if not value:
  811. if keep_blank_values:
  812. value = None
  813. else:
  814. continue
  815. key = unquote(key.replace('+', ' '))
  816. if value:
  817. value = unquote(value.replace('+', ' '))
  818. ret.append((key, value))
  819. return ret
  820. """
  821. # What follows is the OrderedMultiDict from dictutils.py, circa
  822. # 20161021, used for the QueryParamDict, toward the bottom.
  823. """
  824. try:
  825. from collections.abc import KeysView, ValuesView, ItemsView
  826. except ImportError:
  827. from collections import KeysView, ValuesView, ItemsView
  828. try:
  829. from itertools import izip_longest
  830. except ImportError:
  831. from itertools import zip_longest as izip_longest
  832. try:
  833. from .typeutils import make_sentinel
  834. _MISSING = make_sentinel(var_name='_MISSING')
  835. except ImportError:
  836. _MISSING = object()
  837. PREV, NEXT, KEY, VALUE, SPREV, SNEXT = range(6)
  838. class OrderedMultiDict(dict):
  839. """A MultiDict is a dictionary that can have multiple values per key
  840. and the OrderedMultiDict (OMD) is a MultiDict that retains
  841. original insertion order. Common use cases include:
  842. * handling query strings parsed from URLs
  843. * inverting a dictionary to create a reverse index (values to keys)
  844. * stacking data from multiple dictionaries in a non-destructive way
  845. The OrderedMultiDict constructor is identical to the built-in
  846. :class:`dict`, and overall the API is constitutes an intuitive
  847. superset of the built-in type:
  848. >>> omd = OrderedMultiDict()
  849. >>> omd['a'] = 1
  850. >>> omd['b'] = 2
  851. >>> omd.add('a', 3)
  852. >>> omd.get('a')
  853. 3
  854. >>> omd.getlist('a')
  855. [1, 3]
  856. Some non-:class:`dict`-like behaviors also make an appearance,
  857. such as support for :func:`reversed`:
  858. >>> list(reversed(omd))
  859. ['b', 'a']
  860. Note that unlike some other MultiDicts, this OMD gives precedence
  861. to the most recent value added. ``omd['a']`` refers to ``3``, not
  862. ``1``.
  863. >>> omd
  864. OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)])
  865. >>> omd.poplast('a')
  866. 3
  867. >>> omd
  868. OrderedMultiDict([('a', 1), ('b', 2)])
  869. >>> omd.pop('a')
  870. 1
  871. >>> omd
  872. OrderedMultiDict([('b', 2)])
  873. Note that calling :func:`dict` on an OMD results in a dict of keys
  874. to *lists* of values:
  875. >>> from pprint import pprint as pp # ensuring proper key ordering
  876. >>> omd = OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)])
  877. >>> pp(dict(omd))
  878. {'a': 3, 'b': 2}
  879. Note that modifying those lists will modify the OMD. If you want a
  880. safe-to-modify or flat dictionary, use :meth:`OrderedMultiDict.todict()`.
  881. >>> pp(omd.todict())
  882. {'a': 3, 'b': 2}
  883. >>> pp(omd.todict(multi=True))
  884. {'a': [1, 3], 'b': [2]}
  885. With ``multi=False``, items appear with the keys in to original
  886. insertion order, alongside the most-recently inserted value for
  887. that key.
  888. >>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False)
  889. [('a', 3), ('b', 2)]
  890. """
  891. def __init__(self, *args, **kwargs):
  892. if len(args) > 1:
  893. raise TypeError('%s expected at most 1 argument, got %s'
  894. % (self.__class__.__name__, len(args)))
  895. super(OrderedMultiDict, self).__init__()
  896. self._clear_ll()
  897. if args:
  898. self.update_extend(args[0])
  899. if kwargs:
  900. self.update(kwargs)
  901. def _clear_ll(self):
  902. try:
  903. _map = self._map
  904. except AttributeError:
  905. _map = self._map = {}
  906. self.root = []
  907. _map.clear()
  908. self.root[:] = [self.root, self.root, None]
  909. def _insert(self, k, v):
  910. root = self.root
  911. cells = self._map.setdefault(k, [])
  912. last = root[PREV]
  913. cell = [last, root, k, v]
  914. last[NEXT] = root[PREV] = cell
  915. cells.append(cell)
  916. def add(self, k, v):
  917. """Add a single value *v* under a key *k*. Existing values under *k*
  918. are preserved.
  919. """
  920. values = super(OrderedMultiDict, self).setdefault(k, [])
  921. self._insert(k, v)
  922. values.append(v)
  923. def addlist(self, k, v):
  924. """Add an iterable of values underneath a specific key, preserving
  925. any values already under that key.
  926. >>> omd = OrderedMultiDict([('a', -1)])
  927. >>> omd.addlist('a', range(3))
  928. >>> omd
  929. OrderedMultiDict([('a', -1), ('a', 0), ('a', 1), ('a', 2)])
  930. Called ``addlist`` for consistency with :meth:`getlist`, but
  931. tuples and other sequences and iterables work.
  932. """
  933. self_insert = self._insert
  934. values = super(OrderedMultiDict, self).setdefault(k, [])
  935. for subv in v:
  936. self_insert(k, subv)
  937. values.extend(v)
  938. def get(self, k, default=None):
  939. """Return the value for key *k* if present in the dictionary, else
  940. *default*. If *default* is not given, ``None`` is returned.
  941. This method never raises a :exc:`KeyError`.
  942. To get all values under a key, use :meth:`OrderedMultiDict.getlist`.
  943. """
  944. return super(OrderedMultiDict, self).get(k, [default])[-1]
  945. def getlist(self, k, default=_MISSING):
  946. """Get all values for key *k* as a list, if *k* is in the
  947. dictionary, else *default*. The list returned is a copy and
  948. can be safely mutated. If *default* is not given, an empty
  949. :class:`list` is returned.
  950. """
  951. try:
  952. return super(OrderedMultiDict, self).__getitem__(k)[:]
  953. except KeyError:
  954. if default is _MISSING:
  955. return []
  956. return default
  957. def clear(self):
  958. "Empty the dictionary."
  959. super(OrderedMultiDict, self).clear()
  960. self._clear_ll()
  961. def setdefault(self, k, default=_MISSING):
  962. """If key *k* is in the dictionary, return its value. If not, insert
  963. *k* with a value of *default* and return *default*. *default*
  964. defaults to ``None``. See :meth:`dict.setdefault` for more
  965. information.
  966. """
  967. if not super(OrderedMultiDict, self).__contains__(k):
  968. self[k] = None if default is _MISSING else default
  969. return self[k]
  970. def copy(self):
  971. "Return a shallow copy of the dictionary."
  972. return self.__class__(self.iteritems(multi=True))
  973. @classmethod
  974. def fromkeys(cls, keys, default=None):
  975. """Create a dictionary from a list of keys, with all the values
  976. set to *default*, or ``None`` if *default* is not set.
  977. """
  978. return cls([(k, default) for k in keys])
  979. def update(self, E, **F):
  980. """Add items from a dictionary or iterable (and/or keyword arguments),
  981. overwriting values under an existing key. See
  982. :meth:`dict.update` for more details.
  983. """
  984. # E and F are throwback names to the dict() __doc__
  985. if E is self:
  986. return
  987. self_add = self.add
  988. if isinstance(E, OrderedMultiDict):
  989. for k in E:
  990. if k in self:
  991. del self[k]
  992. for k, v in E.iteritems(multi=True):
  993. self_add(k, v)
  994. elif hasattr(E, 'keys'):
  995. for k in E.keys():
  996. self[k] = E[k]
  997. else:
  998. seen = set()
  999. seen_add = seen.add
  1000. for k, v in E:
  1001. if k not in seen and k in self:
  1002. del self[k]
  1003. seen_add(k)
  1004. self_add(k, v)
  1005. for k in F:
  1006. self[k] = F[k]
  1007. return
  1008. def update_extend(self, E, **F):
  1009. """Add items from a dictionary, iterable, and/or keyword
  1010. arguments without overwriting existing items present in the
  1011. dictionary. Like :meth:`update`, but adds to existing keys
  1012. instead of overwriting them.
  1013. """
  1014. if E is self:
  1015. iterator = iter(E.items())
  1016. elif isinstance(E, OrderedMultiDict):
  1017. iterator = E.iteritems(multi=True)
  1018. elif hasattr(E, 'keys'):
  1019. iterator = ((k, E[k]) for k in E.keys())
  1020. else:
  1021. iterator = E
  1022. self_add = self.add
  1023. for k, v in iterator:
  1024. self_add(k, v)
  1025. def __setitem__(self, k, v):
  1026. if super(OrderedMultiDict, self).__contains__(k):
  1027. self._remove_all(k)
  1028. self._insert(k, v)
  1029. super(OrderedMultiDict, self).__setitem__(k, [v])
  1030. def __getitem__(self, k):
  1031. return super(OrderedMultiDict, self).__getitem__(k)[-1]
  1032. def __delitem__(self, k):
  1033. super(OrderedMultiDict, self).__delitem__(k)
  1034. self._remove_all(k)
  1035. def __eq__(self, other):
  1036. if self is other:
  1037. return True
  1038. try:
  1039. if len(other) != len(self):
  1040. return False
  1041. except TypeError:
  1042. return False
  1043. if isinstance(other, OrderedMultiDict):
  1044. selfi = self.iteritems(multi=True)
  1045. otheri = other.iteritems(multi=True)
  1046. zipped_items = izip_longest(selfi, otheri, fillvalue=(None, None))
  1047. for (selfk, selfv), (otherk, otherv) in zipped_items:
  1048. if selfk != otherk or selfv != otherv:
  1049. return False
  1050. if not(next(selfi, _MISSING) is _MISSING
  1051. and next(otheri, _MISSING) is _MISSING):
  1052. # leftovers (TODO: watch for StopIteration?)
  1053. return False
  1054. return True
  1055. elif hasattr(other, 'keys'):
  1056. for selfk in self:
  1057. try:
  1058. other[selfk] == self[selfk]
  1059. except KeyError:
  1060. return False
  1061. return True
  1062. return False
  1063. def __ne__(self, other):
  1064. return not (self == other)
  1065. def pop(self, k, default=_MISSING):
  1066. """Remove all values under key *k*, returning the most-recently
  1067. inserted value. Raises :exc:`KeyError` if the key is not
  1068. present and no *default* is provided.
  1069. """
  1070. try:
  1071. return self.popall(k)[-1]
  1072. except KeyError:
  1073. if default is _MISSING:
  1074. raise KeyError(k)
  1075. return default
  1076. def popall(self, k, default=_MISSING):
  1077. """Remove all values under key *k*, returning them in the form of
  1078. a list. Raises :exc:`KeyError` if the key is not present and no
  1079. *default* is provided.
  1080. """
  1081. super_self = super(OrderedMultiDict, self)
  1082. if super_self.__contains__(k):
  1083. self._remove_all(k)
  1084. if default is _MISSING:
  1085. return super_self.pop(k)
  1086. return super_self.pop(k, default)
  1087. def poplast(self, k=_MISSING, default=_MISSING):
  1088. """Remove and return the most-recently inserted value under the key
  1089. *k*, or the most-recently inserted key if *k* is not
  1090. provided. If no values remain under *k*, it will be removed
  1091. from the OMD. Raises :exc:`KeyError` if *k* is not present in
  1092. the dictionary, or the dictionary is empty.
  1093. """
  1094. if k is _MISSING:
  1095. if self:
  1096. k = self.root[PREV][KEY]
  1097. else:
  1098. raise KeyError('empty %r' % type(self))
  1099. try:
  1100. self._remove(k)
  1101. except KeyError:
  1102. if default is _MISSING:
  1103. raise KeyError(k)
  1104. return default
  1105. values = super(OrderedMultiDict, self).__getitem__(k)
  1106. v = values.pop()
  1107. if not values:
  1108. super(OrderedMultiDict, self).__delitem__(k)
  1109. return v
  1110. def _remove(self, k):
  1111. values = self._map[k]
  1112. cell = values.pop()
  1113. cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV]
  1114. if not values:
  1115. del self._map[k]
  1116. def _remove_all(self, k):
  1117. values = self._map[k]
  1118. while values:
  1119. cell = values.pop()
  1120. cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV]
  1121. del self._map[k]
  1122. def iteritems(self, multi=False):
  1123. """Iterate over the OMD's items in insertion order. By default,
  1124. yields only the most-recently inserted value for each key. Set
  1125. *multi* to ``True`` to get all inserted items.
  1126. """
  1127. root = self.root
  1128. curr = root[NEXT]
  1129. if multi:
  1130. while curr is not root:
  1131. yield curr[KEY], curr[VALUE]
  1132. curr = curr[NEXT]
  1133. else:
  1134. for key in self.iterkeys():
  1135. yield key, self[key]
  1136. def iterkeys(self, multi=False):
  1137. """Iterate over the OMD's keys in insertion order. By default, yields
  1138. each key once, according to the most recent insertion. Set
  1139. *multi* to ``True`` to get all keys, including duplicates, in
  1140. insertion order.
  1141. """
  1142. root = self.root
  1143. curr = root[NEXT]
  1144. if multi:
  1145. while curr is not root:
  1146. yield curr[KEY]
  1147. curr = curr[NEXT]
  1148. else:
  1149. yielded = set()
  1150. yielded_add = yielded.add
  1151. while curr is not root:
  1152. k = curr[KEY]
  1153. if k not in yielded:
  1154. yielded_add(k)
  1155. yield k
  1156. curr = curr[NEXT]
  1157. def itervalues(self, multi=False):
  1158. """Iterate over the OMD's values in insertion order. By default,
  1159. yields the most-recently inserted value per unique key. Set
  1160. *multi* to ``True`` to get all values according to insertion
  1161. order.
  1162. """
  1163. for k, v in self.iteritems(multi=multi):
  1164. yield v
  1165. def todict(self, multi=False):
  1166. """Gets a basic :class:`dict` of the items in this dictionary. Keys
  1167. are the same as the OMD, values are the most recently inserted
  1168. values for each key.
  1169. Setting the *multi* arg to ``True`` is yields the same
  1170. result as calling :class:`dict` on the OMD, except that all the
  1171. value lists are copies that can be safely mutated.
  1172. """
  1173. if multi:
  1174. return dict([(k, self.getlist(k)) for k in self])
  1175. return dict([(k, self[k]) for k in self])
  1176. def sorted(self, key=None, reverse=False):
  1177. """Similar to the built-in :func:`sorted`, except this method returns
  1178. a new :class:`OrderedMultiDict` sorted by the provided key
  1179. function, optionally reversed.
  1180. Args:
  1181. key (callable): A callable to determine the sort key of
  1182. each element. The callable should expect an **item**
  1183. (key-value pair tuple).
  1184. reverse (bool): Set to ``True`` to reverse the ordering.
  1185. >>> omd = OrderedMultiDict(zip(range(3), range(3)))
  1186. >>> omd.sorted(reverse=True)
  1187. OrderedMultiDict([(2, 2), (1, 1), (0, 0)])
  1188. Note that the key function receives an **item** (key-value
  1189. tuple), so the recommended signature looks like:
  1190. >>> omd = OrderedMultiDict(zip('hello', 'world'))
  1191. >>> omd.sorted(key=lambda i: i[1]) # i[0] is the key, i[1] is the val
  1192. OrderedMultiDict([('o', 'd'), ('l', 'l'), ('e', 'o'), ('l', 'r'), ('h', 'w')])
  1193. """
  1194. cls = self.__class__
  1195. return cls(sorted(self.iteritems(), key=key, reverse=reverse))
  1196. def sortedvalues(self, key=None, reverse=False):
  1197. """Returns a copy of the :class:`OrderedMultiDict` with the same keys
  1198. in the same order as the original OMD, but the values within
  1199. each keyspace have been sorted according to *key* and
  1200. *reverse*.
  1201. Args:
  1202. key (callable): A single-argument callable to determine
  1203. the sort key of each element. The callable should expect
  1204. an **item** (key-value pair tuple).
  1205. reverse (bool): Set to ``True`` to reverse the ordering.
  1206. >>> omd = OrderedMultiDict()
  1207. >>> omd.addlist('even', [6, 2])
  1208. >>> omd.addlist('odd', [1, 5])
  1209. >>> omd.add('even', 4)
  1210. >>> omd.add('odd', 3)
  1211. >>> somd = omd.sortedvalues()
  1212. >>> somd.getlist('even')
  1213. [2, 4, 6]
  1214. >>> somd.keys(multi=True) == omd.keys(multi=True)
  1215. True
  1216. >>> omd == somd
  1217. False
  1218. >>> somd
  1219. OrderedMultiDict([('even', 2), ('even', 4), ('odd', 1), ('odd', 3), ('even', 6), ('odd', 5)])
  1220. As demonstrated above, contents and key order are
  1221. retained. Only value order changes.
  1222. """
  1223. try:
  1224. superself_iteritems = super(OrderedMultiDict, self).iteritems()
  1225. except AttributeError:
  1226. superself_iteritems = super(OrderedMultiDict, self).items()
  1227. # (not reverse) because they pop off in reverse order for reinsertion
  1228. sorted_val_map = dict([(k, sorted(v, key=key, reverse=(not reverse)))
  1229. for k, v in superself_iteritems])
  1230. ret = self.__class__()
  1231. for k in self.iterkeys(multi=True):
  1232. ret.add(k, sorted_val_map[k].pop())
  1233. return ret
  1234. def inverted(self):
  1235. """Returns a new :class:`OrderedMultiDict` with values and keys
  1236. swapped, like creating dictionary transposition or reverse
  1237. index. Insertion order is retained and all keys and values
  1238. are represented in the output.
  1239. >>> omd = OMD([(0, 2), (1, 2)])
  1240. >>> omd.inverted().getlist(2)
  1241. [0, 1]
  1242. Inverting twice yields a copy of the original:
  1243. >>> omd.inverted().inverted()
  1244. OrderedMultiDict([(0, 2), (1, 2)])
  1245. """
  1246. return self.__class__((v, k) for k, v in self.iteritems(multi=True))
  1247. def counts(self):
  1248. """Returns a mapping from key to number of values inserted under that
  1249. key. Like :py:class:`collections.Counter`, but returns a new
  1250. :class:`OrderedMultiDict`.
  1251. """
  1252. # Returns an OMD because Counter/OrderedDict may not be
  1253. # available, and neither Counter nor dict maintain order.
  1254. super_getitem = super(OrderedMultiDict, self).__getitem__
  1255. return self.__class__((k, len(super_getitem(k))) for k in self)
  1256. def keys(self, multi=False):
  1257. """Returns a list containing the output of :meth:`iterkeys`. See
  1258. that method's docs for more details.
  1259. """
  1260. return list(self.iterkeys(multi=multi))
  1261. def values(self, multi=False):
  1262. """Returns a list containing the output of :meth:`itervalues`. See
  1263. that method's docs for more details.
  1264. """
  1265. return list(self.itervalues(multi=multi))
  1266. def items(self, multi=False):
  1267. """Returns a list containing the output of :meth:`iteritems`. See
  1268. that method's docs for more details.
  1269. """
  1270. return list(self.iteritems(multi=multi))
  1271. def __iter__(self):
  1272. return self.iterkeys()
  1273. def __reversed__(self):
  1274. root = self.root
  1275. curr = root[PREV]
  1276. lengths = {}
  1277. lengths_sd = lengths.setdefault
  1278. get_values = super(OrderedMultiDict, self).__getitem__
  1279. while curr is not root:
  1280. k = curr[KEY]
  1281. vals = get_values(k)
  1282. if lengths_sd(k, 1) == len(vals):
  1283. yield k
  1284. lengths[k] += 1
  1285. curr = curr[PREV]
  1286. def __repr__(self):
  1287. cn = self.__class__.__name__
  1288. kvs = ', '.join([repr((k, v)) for k, v in self.iteritems(multi=True)])
  1289. return '%s([%s])' % (cn, kvs)
  1290. def viewkeys(self):
  1291. "OMD.viewkeys() -> a set-like object providing a view on OMD's keys"
  1292. return KeysView(self)
  1293. def viewvalues(self):
  1294. "OMD.viewvalues() -> an object providing a view on OMD's values"
  1295. return ValuesView(self)
  1296. def viewitems(self):
  1297. "OMD.viewitems() -> a set-like object providing a view on OMD's items"
  1298. return ItemsView(self)
  1299. try:
  1300. # try to import the built-in one anyways
  1301. from .dictutils import OrderedMultiDict
  1302. except ImportError:
  1303. pass
  1304. OMD = OrderedMultiDict
  1305. class QueryParamDict(OrderedMultiDict):
  1306. """A subclass of :class:`~dictutils.OrderedMultiDict` specialized for
  1307. representing query string values. Everything is fully unquoted on
  1308. load and all parsed keys and values are strings by default.
  1309. As the name suggests, multiple values are supported and insertion
  1310. order is preserved.
  1311. >>> qp = QueryParamDict.from_text(u'key=val1&key=val2&utm_source=rtd')
  1312. >>> qp.getlist('key')
  1313. [u'val1', u'val2']
  1314. >>> qp['key']
  1315. u'val2'
  1316. >>> qp.add('key', 'val3')
  1317. >>> qp.to_text()
  1318. 'key=val1&key=val2&utm_source=rtd&key=val3'
  1319. See :class:`~dictutils.OrderedMultiDict` for more API features.
  1320. """
  1321. @classmethod
  1322. def from_text(cls, query_string):
  1323. """
  1324. Parse *query_string* and return a new :class:`QueryParamDict`.
  1325. """
  1326. pairs = parse_qsl(query_string, keep_blank_values=True)
  1327. return cls(pairs)
  1328. def to_text(self, full_quote=False):
  1329. """
  1330. Render and return a query string.
  1331. Args:
  1332. full_quote (bool): Whether or not to percent-quote special
  1333. characters or leave them decoded for readability.
  1334. """
  1335. ret_list = []
  1336. for k, v in self.iteritems(multi=True):
  1337. key = quote_query_part(to_unicode(k), full_quote=full_quote)
  1338. if v is None:
  1339. ret_list.append(key)
  1340. else:
  1341. val = quote_query_part(to_unicode(v), full_quote=full_quote)
  1342. ret_list.append(u'='.join((key, val)))
  1343. return u'&'.join(ret_list)
  1344. # TODO: cleanup OMD/cachedproperty etc.?
  1345. # end urlutils.py