_urls.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. from __future__ import annotations
  2. import typing
  3. from urllib.parse import parse_qs, unquote, urlencode
  4. import idna
  5. from ._types import QueryParamTypes
  6. from ._urlparse import urlparse
  7. from ._utils import primitive_value_to_str
  8. __all__ = ["URL", "QueryParams"]
  9. class URL:
  10. """
  11. url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")
  12. assert url.scheme == "https"
  13. assert url.username == "jo@email.com"
  14. assert url.password == "a secret"
  15. assert url.userinfo == b"jo%40email.com:a%20secret"
  16. assert url.host == "müller.de"
  17. assert url.raw_host == b"xn--mller-kva.de"
  18. assert url.port == 1234
  19. assert url.netloc == b"xn--mller-kva.de:1234"
  20. assert url.path == "/pa th"
  21. assert url.query == b"?search=ab"
  22. assert url.raw_path == b"/pa%20th?search=ab"
  23. assert url.fragment == "anchorlink"
  24. The components of a URL are broken down like this:
  25. https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink
  26. [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment]
  27. [ userinfo ] [ netloc ][ raw_path ]
  28. Note that:
  29. * `url.scheme` is normalized to always be lowercased.
  30. * `url.host` is normalized to always be lowercased. Internationalized domain
  31. names are represented in unicode, without IDNA encoding applied. For instance:
  32. url = httpx.URL("http://中国.icom.museum")
  33. assert url.host == "中国.icom.museum"
  34. url = httpx.URL("http://xn--fiqs8s.icom.museum")
  35. assert url.host == "中国.icom.museum"
  36. * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.
  37. url = httpx.URL("http://中国.icom.museum")
  38. assert url.raw_host == b"xn--fiqs8s.icom.museum"
  39. url = httpx.URL("http://xn--fiqs8s.icom.museum")
  40. assert url.raw_host == b"xn--fiqs8s.icom.museum"
  41. * `url.port` is either None or an integer. URLs that include the default port for
  42. "http", "https", "ws", "wss", and "ftp" schemes have their port
  43. normalized to `None`.
  44. assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80")
  45. assert httpx.URL("http://example.com").port is None
  46. assert httpx.URL("http://example.com:80").port is None
  47. * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work
  48. with `url.username` and `url.password` instead, which handle the URL escaping.
  49. * `url.raw_path` is raw bytes of both the path and query, without URL escaping.
  50. This portion is used as the target when constructing HTTP requests. Usually you'll
  51. want to work with `url.path` instead.
  52. * `url.query` is raw bytes, without URL escaping. A URL query string portion can
  53. only be properly URL escaped when decoding the parameter names and values
  54. themselves.
  55. """
  56. def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None:
  57. if kwargs:
  58. allowed = {
  59. "scheme": str,
  60. "username": str,
  61. "password": str,
  62. "userinfo": bytes,
  63. "host": str,
  64. "port": int,
  65. "netloc": bytes,
  66. "path": str,
  67. "query": bytes,
  68. "raw_path": bytes,
  69. "fragment": str,
  70. "params": object,
  71. }
  72. # Perform type checking for all supported keyword arguments.
  73. for key, value in kwargs.items():
  74. if key not in allowed:
  75. message = f"{key!r} is an invalid keyword argument for URL()"
  76. raise TypeError(message)
  77. if value is not None and not isinstance(value, allowed[key]):
  78. expected = allowed[key].__name__
  79. seen = type(value).__name__
  80. message = f"Argument {key!r} must be {expected} but got {seen}"
  81. raise TypeError(message)
  82. if isinstance(value, bytes):
  83. kwargs[key] = value.decode("ascii")
  84. if "params" in kwargs:
  85. # Replace any "params" keyword with the raw "query" instead.
  86. #
  87. # Ensure that empty params use `kwargs["query"] = None` rather
  88. # than `kwargs["query"] = ""`, so that generated URLs do not
  89. # include an empty trailing "?".
  90. params = kwargs.pop("params")
  91. kwargs["query"] = None if not params else str(QueryParams(params))
  92. if isinstance(url, str):
  93. self._uri_reference = urlparse(url, **kwargs)
  94. elif isinstance(url, URL):
  95. self._uri_reference = url._uri_reference.copy_with(**kwargs)
  96. else:
  97. raise TypeError(
  98. "Invalid type for url. Expected str or httpx.URL,"
  99. f" got {type(url)}: {url!r}"
  100. )
  101. @property
  102. def scheme(self) -> str:
  103. """
  104. The URL scheme, such as "http", "https".
  105. Always normalised to lowercase.
  106. """
  107. return self._uri_reference.scheme
  108. @property
  109. def raw_scheme(self) -> bytes:
  110. """
  111. The raw bytes representation of the URL scheme, such as b"http", b"https".
  112. Always normalised to lowercase.
  113. """
  114. return self._uri_reference.scheme.encode("ascii")
  115. @property
  116. def userinfo(self) -> bytes:
  117. """
  118. The URL userinfo as a raw bytestring.
  119. For example: b"jo%40email.com:a%20secret".
  120. """
  121. return self._uri_reference.userinfo.encode("ascii")
  122. @property
  123. def username(self) -> str:
  124. """
  125. The URL username as a string, with URL decoding applied.
  126. For example: "jo@email.com"
  127. """
  128. userinfo = self._uri_reference.userinfo
  129. return unquote(userinfo.partition(":")[0])
  130. @property
  131. def password(self) -> str:
  132. """
  133. The URL password as a string, with URL decoding applied.
  134. For example: "a secret"
  135. """
  136. userinfo = self._uri_reference.userinfo
  137. return unquote(userinfo.partition(":")[2])
  138. @property
  139. def host(self) -> str:
  140. """
  141. The URL host as a string.
  142. Always normalized to lowercase, with IDNA hosts decoded into unicode.
  143. Examples:
  144. url = httpx.URL("http://www.EXAMPLE.org")
  145. assert url.host == "www.example.org"
  146. url = httpx.URL("http://中国.icom.museum")
  147. assert url.host == "中国.icom.museum"
  148. url = httpx.URL("http://xn--fiqs8s.icom.museum")
  149. assert url.host == "中国.icom.museum"
  150. url = httpx.URL("https://[::ffff:192.168.0.1]")
  151. assert url.host == "::ffff:192.168.0.1"
  152. """
  153. host: str = self._uri_reference.host
  154. if host.startswith("xn--"):
  155. host = idna.decode(host)
  156. return host
  157. @property
  158. def raw_host(self) -> bytes:
  159. """
  160. The raw bytes representation of the URL host.
  161. Always normalized to lowercase, and IDNA encoded.
  162. Examples:
  163. url = httpx.URL("http://www.EXAMPLE.org")
  164. assert url.raw_host == b"www.example.org"
  165. url = httpx.URL("http://中国.icom.museum")
  166. assert url.raw_host == b"xn--fiqs8s.icom.museum"
  167. url = httpx.URL("http://xn--fiqs8s.icom.museum")
  168. assert url.raw_host == b"xn--fiqs8s.icom.museum"
  169. url = httpx.URL("https://[::ffff:192.168.0.1]")
  170. assert url.raw_host == b"::ffff:192.168.0.1"
  171. """
  172. return self._uri_reference.host.encode("ascii")
  173. @property
  174. def port(self) -> int | None:
  175. """
  176. The URL port as an integer.
  177. Note that the URL class performs port normalization as per the WHATWG spec.
  178. Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always
  179. treated as `None`.
  180. For example:
  181. assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80")
  182. assert httpx.URL("http://www.example.com:80").port is None
  183. """
  184. return self._uri_reference.port
  185. @property
  186. def netloc(self) -> bytes:
  187. """
  188. Either `<host>` or `<host>:<port>` as bytes.
  189. Always normalized to lowercase, and IDNA encoded.
  190. This property may be used for generating the value of a request
  191. "Host" header.
  192. """
  193. return self._uri_reference.netloc.encode("ascii")
  194. @property
  195. def path(self) -> str:
  196. """
  197. The URL path as a string. Excluding the query string, and URL decoded.
  198. For example:
  199. url = httpx.URL("https://example.com/pa%20th")
  200. assert url.path == "/pa th"
  201. """
  202. path = self._uri_reference.path or "/"
  203. return unquote(path)
  204. @property
  205. def query(self) -> bytes:
  206. """
  207. The URL query string, as raw bytes, excluding the leading b"?".
  208. This is necessarily a bytewise interface, because we cannot
  209. perform URL decoding of this representation until we've parsed
  210. the keys and values into a QueryParams instance.
  211. For example:
  212. url = httpx.URL("https://example.com/?filter=some%20search%20terms")
  213. assert url.query == b"filter=some%20search%20terms"
  214. """
  215. query = self._uri_reference.query or ""
  216. return query.encode("ascii")
  217. @property
  218. def params(self) -> QueryParams:
  219. """
  220. The URL query parameters, neatly parsed and packaged into an immutable
  221. multidict representation.
  222. """
  223. return QueryParams(self._uri_reference.query)
  224. @property
  225. def raw_path(self) -> bytes:
  226. """
  227. The complete URL path and query string as raw bytes.
  228. Used as the target when constructing HTTP requests.
  229. For example:
  230. GET /users?search=some%20text HTTP/1.1
  231. Host: www.example.org
  232. Connection: close
  233. """
  234. path = self._uri_reference.path or "/"
  235. if self._uri_reference.query is not None:
  236. path += "?" + self._uri_reference.query
  237. return path.encode("ascii")
  238. @property
  239. def fragment(self) -> str:
  240. """
  241. The URL fragments, as used in HTML anchors.
  242. As a string, without the leading '#'.
  243. """
  244. return unquote(self._uri_reference.fragment or "")
  245. @property
  246. def is_absolute_url(self) -> bool:
  247. """
  248. Return `True` for absolute URLs such as 'http://example.com/path',
  249. and `False` for relative URLs such as '/path'.
  250. """
  251. # We don't use `.is_absolute` from `rfc3986` because it treats
  252. # URLs with a fragment portion as not absolute.
  253. # What we actually care about is if the URL provides
  254. # a scheme and hostname to which connections should be made.
  255. return bool(self._uri_reference.scheme and self._uri_reference.host)
  256. @property
  257. def is_relative_url(self) -> bool:
  258. """
  259. Return `False` for absolute URLs such as 'http://example.com/path',
  260. and `True` for relative URLs such as '/path'.
  261. """
  262. return not self.is_absolute_url
  263. def copy_with(self, **kwargs: typing.Any) -> URL:
  264. """
  265. Copy this URL, returning a new URL with some components altered.
  266. Accepts the same set of parameters as the components that are made
  267. available via properties on the `URL` class.
  268. For example:
  269. url = httpx.URL("https://www.example.com").copy_with(
  270. username="jo@gmail.com", password="a secret"
  271. )
  272. assert url == "https://jo%40email.com:a%20secret@www.example.com"
  273. """
  274. return URL(self, **kwargs)
  275. def copy_set_param(self, key: str, value: typing.Any = None) -> URL:
  276. return self.copy_with(params=self.params.set(key, value))
  277. def copy_add_param(self, key: str, value: typing.Any = None) -> URL:
  278. return self.copy_with(params=self.params.add(key, value))
  279. def copy_remove_param(self, key: str) -> URL:
  280. return self.copy_with(params=self.params.remove(key))
  281. def copy_merge_params(self, params: QueryParamTypes) -> URL:
  282. return self.copy_with(params=self.params.merge(params))
  283. def join(self, url: URL | str) -> URL:
  284. """
  285. Return an absolute URL, using this URL as the base.
  286. Eg.
  287. url = httpx.URL("https://www.example.com/test")
  288. url = url.join("/new/path")
  289. assert url == "https://www.example.com/new/path"
  290. """
  291. from urllib.parse import urljoin
  292. return URL(urljoin(str(self), str(URL(url))))
  293. def __hash__(self) -> int:
  294. return hash(str(self))
  295. def __eq__(self, other: typing.Any) -> bool:
  296. return isinstance(other, (URL, str)) and str(self) == str(URL(other))
  297. def __str__(self) -> str:
  298. return str(self._uri_reference)
  299. def __repr__(self) -> str:
  300. scheme, userinfo, host, port, path, query, fragment = self._uri_reference
  301. if ":" in userinfo:
  302. # Mask any password component.
  303. userinfo = f'{userinfo.split(":")[0]}:[secure]'
  304. authority = "".join(
  305. [
  306. f"{userinfo}@" if userinfo else "",
  307. f"[{host}]" if ":" in host else host,
  308. f":{port}" if port is not None else "",
  309. ]
  310. )
  311. url = "".join(
  312. [
  313. f"{self.scheme}:" if scheme else "",
  314. f"//{authority}" if authority else "",
  315. path,
  316. f"?{query}" if query is not None else "",
  317. f"#{fragment}" if fragment is not None else "",
  318. ]
  319. )
  320. return f"{self.__class__.__name__}({url!r})"
  321. @property
  322. def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover
  323. import collections
  324. import warnings
  325. warnings.warn("URL.raw is deprecated.")
  326. RawURL = collections.namedtuple(
  327. "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"]
  328. )
  329. return RawURL(
  330. raw_scheme=self.raw_scheme,
  331. raw_host=self.raw_host,
  332. port=self.port,
  333. raw_path=self.raw_path,
  334. )
  335. class QueryParams(typing.Mapping[str, str]):
  336. """
  337. URL query parameters, as a multi-dict.
  338. """
  339. def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None:
  340. assert len(args) < 2, "Too many arguments."
  341. assert not (args and kwargs), "Cannot mix named and unnamed arguments."
  342. value = args[0] if args else kwargs
  343. if value is None or isinstance(value, (str, bytes)):
  344. value = value.decode("ascii") if isinstance(value, bytes) else value
  345. self._dict = parse_qs(value, keep_blank_values=True)
  346. elif isinstance(value, QueryParams):
  347. self._dict = {k: list(v) for k, v in value._dict.items()}
  348. else:
  349. dict_value: dict[typing.Any, list[typing.Any]] = {}
  350. if isinstance(value, (list, tuple)):
  351. # Convert list inputs like:
  352. # [("a", "123"), ("a", "456"), ("b", "789")]
  353. # To a dict representation, like:
  354. # {"a": ["123", "456"], "b": ["789"]}
  355. for item in value:
  356. dict_value.setdefault(item[0], []).append(item[1])
  357. else:
  358. # Convert dict inputs like:
  359. # {"a": "123", "b": ["456", "789"]}
  360. # To dict inputs where values are always lists, like:
  361. # {"a": ["123"], "b": ["456", "789"]}
  362. dict_value = {
  363. k: list(v) if isinstance(v, (list, tuple)) else [v]
  364. for k, v in value.items()
  365. }
  366. # Ensure that keys and values are neatly coerced to strings.
  367. # We coerce values `True` and `False` to JSON-like "true" and "false"
  368. # representations, and coerce `None` values to the empty string.
  369. self._dict = {
  370. str(k): [primitive_value_to_str(item) for item in v]
  371. for k, v in dict_value.items()
  372. }
  373. def keys(self) -> typing.KeysView[str]:
  374. """
  375. Return all the keys in the query params.
  376. Usage:
  377. q = httpx.QueryParams("a=123&a=456&b=789")
  378. assert list(q.keys()) == ["a", "b"]
  379. """
  380. return self._dict.keys()
  381. def values(self) -> typing.ValuesView[str]:
  382. """
  383. Return all the values in the query params. If a key occurs more than once
  384. only the first item for that key is returned.
  385. Usage:
  386. q = httpx.QueryParams("a=123&a=456&b=789")
  387. assert list(q.values()) == ["123", "789"]
  388. """
  389. return {k: v[0] for k, v in self._dict.items()}.values()
  390. def items(self) -> typing.ItemsView[str, str]:
  391. """
  392. Return all items in the query params. If a key occurs more than once
  393. only the first item for that key is returned.
  394. Usage:
  395. q = httpx.QueryParams("a=123&a=456&b=789")
  396. assert list(q.items()) == [("a", "123"), ("b", "789")]
  397. """
  398. return {k: v[0] for k, v in self._dict.items()}.items()
  399. def multi_items(self) -> list[tuple[str, str]]:
  400. """
  401. Return all items in the query params. Allow duplicate keys to occur.
  402. Usage:
  403. q = httpx.QueryParams("a=123&a=456&b=789")
  404. assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")]
  405. """
  406. multi_items: list[tuple[str, str]] = []
  407. for k, v in self._dict.items():
  408. multi_items.extend([(k, i) for i in v])
  409. return multi_items
  410. def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
  411. """
  412. Get a value from the query param for a given key. If the key occurs
  413. more than once, then only the first value is returned.
  414. Usage:
  415. q = httpx.QueryParams("a=123&a=456&b=789")
  416. assert q.get("a") == "123"
  417. """
  418. if key in self._dict:
  419. return self._dict[str(key)][0]
  420. return default
  421. def get_list(self, key: str) -> list[str]:
  422. """
  423. Get all values from the query param for a given key.
  424. Usage:
  425. q = httpx.QueryParams("a=123&a=456&b=789")
  426. assert q.get_list("a") == ["123", "456"]
  427. """
  428. return list(self._dict.get(str(key), []))
  429. def set(self, key: str, value: typing.Any = None) -> QueryParams:
  430. """
  431. Return a new QueryParams instance, setting the value of a key.
  432. Usage:
  433. q = httpx.QueryParams("a=123")
  434. q = q.set("a", "456")
  435. assert q == httpx.QueryParams("a=456")
  436. """
  437. q = QueryParams()
  438. q._dict = dict(self._dict)
  439. q._dict[str(key)] = [primitive_value_to_str(value)]
  440. return q
  441. def add(self, key: str, value: typing.Any = None) -> QueryParams:
  442. """
  443. Return a new QueryParams instance, setting or appending the value of a key.
  444. Usage:
  445. q = httpx.QueryParams("a=123")
  446. q = q.add("a", "456")
  447. assert q == httpx.QueryParams("a=123&a=456")
  448. """
  449. q = QueryParams()
  450. q._dict = dict(self._dict)
  451. q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]
  452. return q
  453. def remove(self, key: str) -> QueryParams:
  454. """
  455. Return a new QueryParams instance, removing the value of a key.
  456. Usage:
  457. q = httpx.QueryParams("a=123")
  458. q = q.remove("a")
  459. assert q == httpx.QueryParams("")
  460. """
  461. q = QueryParams()
  462. q._dict = dict(self._dict)
  463. q._dict.pop(str(key), None)
  464. return q
  465. def merge(self, params: QueryParamTypes | None = None) -> QueryParams:
  466. """
  467. Return a new QueryParams instance, updated with.
  468. Usage:
  469. q = httpx.QueryParams("a=123")
  470. q = q.merge({"b": "456"})
  471. assert q == httpx.QueryParams("a=123&b=456")
  472. q = httpx.QueryParams("a=123")
  473. q = q.merge({"a": "456", "b": "789"})
  474. assert q == httpx.QueryParams("a=456&b=789")
  475. """
  476. q = QueryParams(params)
  477. q._dict = {**self._dict, **q._dict}
  478. return q
  479. def __getitem__(self, key: typing.Any) -> str:
  480. return self._dict[key][0]
  481. def __contains__(self, key: typing.Any) -> bool:
  482. return key in self._dict
  483. def __iter__(self) -> typing.Iterator[typing.Any]:
  484. return iter(self.keys())
  485. def __len__(self) -> int:
  486. return len(self._dict)
  487. def __bool__(self) -> bool:
  488. return bool(self._dict)
  489. def __hash__(self) -> int:
  490. return hash(str(self))
  491. def __eq__(self, other: typing.Any) -> bool:
  492. if not isinstance(other, self.__class__):
  493. return False
  494. return sorted(self.multi_items()) == sorted(other.multi_items())
  495. def __str__(self) -> str:
  496. return urlencode(self.multi_items())
  497. def __repr__(self) -> str:
  498. class_name = self.__class__.__name__
  499. query_string = str(self)
  500. return f"{class_name}({query_string!r})"
  501. def update(self, params: QueryParamTypes | None = None) -> None:
  502. raise RuntimeError(
  503. "QueryParams are immutable since 0.18.0. "
  504. "Use `q = q.merge(...)` to create an updated copy."
  505. )
  506. def __setitem__(self, key: str, value: str) -> None:
  507. raise RuntimeError(
  508. "QueryParams are immutable since 0.18.0. "
  509. "Use `q = q.set(key, value)` to create an updated copy."
  510. )