Skip to content
Myr

Move URL and QueryParams to new '_urls.py' module (#2084)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent 2072aa2 · Browse files · 5 files+780 added−774 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+780 added−774 removed

  • other:+780 added−774 removed

5 files+780 added−774 removed

modified:httpx/__init__.py+2 added-1 removed
32 unmodified lines
33 UnsupportedProtocol,34 WriteError,35 WriteTimeout,36)37from ._models import URL, Cookies, Headers, QueryParams, Request, Response37from ._models import Cookies, Headers, Request, Response38from ._status_codes import codes39from ._transports.asgi import ASGITransport40from ._transports.base import AsyncBaseTransport, BaseTransport41from ._transports.default import AsyncHTTPTransport, HTTPTransport42from ._transports.mock import MockTransport43from ._transports.wsgi import WSGITransport44from ._types import AsyncByteStream, SyncByteStream45from ._urls import URL, QueryParams4647try:48 from ._main import main49except ImportError: # pragma: nocover
88 unmodified lines
modified:httpx/_client.py+2 added-1 removed
21 unmodified lines
22 RemoteProtocolError,23 TooManyRedirects,24 request_context,25)26from ._models import URL, Cookies, Headers, QueryParams, Request, Response26from ._models import Cookies, Headers, Request, Response27from ._status_codes import codes28from ._transports.asgi import ASGITransport29from ._transports.base import AsyncBaseTransport, BaseTransport30from ._transports.default import AsyncHTTPTransport, HTTPTransport
13 unmodified lines
44 TimeoutTypes,45 URLTypes,46 VerifyTypes,47)48from ._urls import URL, QueryParams49from ._utils import (50 NetRCInfo,51 Timer,52 URLPattern,
1929 unmodified lines
modified:httpx/_models.py+1 added-771 removed
4 unmodified lines
5import typing6import urllib.request7from collections.abc import MutableMapping8from http.cookiejar import Cookie, CookieJar9from urllib.parse import parse_qs, quote, unquote, urlencode910import charset_normalizer12import idna13import rfc398614import rfc3986.exceptions1112from ._content import ByteStream, UnattachedStream, encode_request, encode_response13from ._decoders import (14 SUPPORTED_DECODERS,
7 unmodified lines
22)23from ._exceptions import (24 CookieConflict,25 HTTPStatusError,30 InvalidURL,26 RequestNotRead,27 ResponseNotRead,28 StreamClosed,29 StreamConsumed,
3 unmodified lines
33from ._types import (34 AsyncByteStream,35 CookieTypes,36 HeaderTypes,42 PrimitiveData,37 QueryParamTypes,38 RawURL,39 RequestContent,40 RequestData,41 RequestFiles,42 ResponseContent,43 SyncByteStream,50 URLTypes,44)45from ._urls import URL46from ._utils import (47 guess_json_utf,48 is_known_encoding,49 normalize_header_key,50 normalize_header_value,51 obfuscate_sensitive_headers,52 parse_header_links,59 primitive_value_to_str,53)545563class URL:64 """65 url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")6667 assert url.scheme == "https"68 assert url.username == "jo@email.com"69 assert url.password == "a secret"70 assert url.userinfo == b"jo%40email.com:a%20secret"71 assert url.host == "müller.de"72 assert url.raw_host == b"xn--mller-kva.de"73 assert url.port == 123474 assert url.netloc == b"xn--mller-kva.de:1234"75 assert url.path == "/pa th"76 assert url.query == b"?search=ab"77 assert url.raw_path == b"/pa%20th?search=ab"78 assert url.fragment == "anchorlink"7980 The components of a URL are broken down like this:8182 https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink83 [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment]84 [ userinfo ] [ netloc ][ raw_path ]8586 Note that:8788 * `url.scheme` is normalized to always be lowercased.8990 * `url.host` is normalized to always be lowercased. Internationalized domain91 names are represented in unicode, without IDNA encoding applied. For instance:9293 url = httpx.URL("http://中国.icom.museum")94 assert url.host == "中国.icom.museum"95 url = httpx.URL("http://xn--fiqs8s.icom.museum")96 assert url.host == "中国.icom.museum"9798 * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.99100 url = httpx.URL("http://中国.icom.museum")101 assert url.raw_host == b"xn--fiqs8s.icom.museum"102 url = httpx.URL("http://xn--fiqs8s.icom.museum")103 assert url.raw_host == b"xn--fiqs8s.icom.museum"104105 * `url.port` is either None or an integer. URLs that include the default port for106 "http", "https", "ws", "wss", and "ftp" schemes have their port normalized to `None`.107108 assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80")109 assert httpx.URL("http://example.com").port is None110 assert httpx.URL("http://example.com:80").port is None111112 * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work with113 `url.username` and `url.password` instead, which handle the URL escaping.114115 * `url.raw_path` is raw bytes of both the path and query, without URL escaping.116 This portion is used as the target when constructing HTTP requests. Usually you'll117 want to work with `url.path` instead.118119 * `url.query` is raw bytes, without URL escaping. A URL query string portion can only120 be properly URL escaped when decoding the parameter names and values themselves.121 """122123 def __init__(124 self, url: typing.Union["URL", str, RawURL] = "", **kwargs: typing.Any125 ) -> None:126 if isinstance(url, (str, tuple)):127 if isinstance(url, tuple):128 raw_scheme, raw_host, port, raw_path = url129 scheme = raw_scheme.decode("ascii")130 host = raw_host.decode("ascii")131 if host and ":" in host and host[0] != "[":132 # it's an IPv6 address, so it should be enclosed in "[" and "]"133 # ref: https://tools.ietf.org/html/rfc2732#section-2134 # ref: https://tools.ietf.org/html/rfc3986#section-3.2.2135 host = f"[{host}]"136 port_str = "" if port is None else f":{port}"137 path = raw_path.decode("ascii")138 url = f"{scheme}://{host}{port_str}{path}"139140 try:141 self._uri_reference = rfc3986.iri_reference(url).encode()142 except rfc3986.exceptions.InvalidAuthority as exc:143 raise InvalidURL(message=str(exc)) from None144145 if self.is_absolute_url:146 # We don't want to normalize relative URLs, since doing so147 # removes any leading `../` portion.148 self._uri_reference = self._uri_reference.normalize()149 elif isinstance(url, URL):150 self._uri_reference = url._uri_reference151 else:152 raise TypeError(153 f"Invalid type for url. Expected str or httpx.URL, got {type(url)}: {url!r}"154 )155156 # Perform port normalization, following the WHATWG spec for default ports.157 #158 # See:159 # * https://tools.ietf.org/html/rfc3986#section-3.2.3160 # * https://url.spec.whatwg.org/#url-miscellaneous161 # * https://url.spec.whatwg.org/#scheme-state162 default_port = {163 "ftp": ":21",164 "http": ":80",165 "https": ":443",166 "ws": ":80",167 "wss": ":443",168 }.get(self._uri_reference.scheme, "")169 authority = self._uri_reference.authority or ""170 if default_port and authority.endswith(default_port):171 authority = authority[: -len(default_port)]172 self._uri_reference = self._uri_reference.copy_with(authority=authority)173174 if kwargs:175 self._uri_reference = self.copy_with(**kwargs)._uri_reference176177 @property178 def scheme(self) -> str:179 """180 The URL scheme, such as "http", "https".181 Always normalised to lowercase.182 """183 return self._uri_reference.scheme or ""184185 @property186 def raw_scheme(self) -> bytes:187 """188 The raw bytes representation of the URL scheme, such as b"http", b"https".189 Always normalised to lowercase.190 """191 return self.scheme.encode("ascii")192193 @property194 def userinfo(self) -> bytes:195 """196 The URL userinfo as a raw bytestring.197 For example: b"jo%40email.com:a%20secret".198 """199 userinfo = self._uri_reference.userinfo or ""200 return userinfo.encode("ascii")201202 @property203 def username(self) -> str:204 """205 The URL username as a string, with URL decoding applied.206 For example: "jo@email.com"207 """208 userinfo = self._uri_reference.userinfo or ""209 return unquote(userinfo.partition(":")[0])210211 @property212 def password(self) -> str:213 """214 The URL password as a string, with URL decoding applied.215 For example: "a secret"216 """217 userinfo = self._uri_reference.userinfo or ""218 return unquote(userinfo.partition(":")[2])219220 @property221 def host(self) -> str:222 """223 The URL host as a string.224 Always normalized to lowercase, with IDNA hosts decoded into unicode.225226 Examples:227228 url = httpx.URL("http://www.EXAMPLE.org")229 assert url.host == "www.example.org"230231 url = httpx.URL("http://中国.icom.museum")232 assert url.host == "中国.icom.museum"233234 url = httpx.URL("http://xn--fiqs8s.icom.museum")235 assert url.host == "中国.icom.museum"236237 url = httpx.URL("https://[::ffff:192.168.0.1]")238 assert url.host == "::ffff:192.168.0.1"239 """240 host: str = self._uri_reference.host or ""241242 if host and ":" in host and host[0] == "[":243 # it's an IPv6 address244 host = host.lstrip("[").rstrip("]")245246 if host.startswith("xn--"):247 host = idna.decode(host)248249 return host250251 @property252 def raw_host(self) -> bytes:253 """254 The raw bytes representation of the URL host.255 Always normalized to lowercase, and IDNA encoded.256257 Examples:258259 url = httpx.URL("http://www.EXAMPLE.org")260 assert url.raw_host == b"www.example.org"261262 url = httpx.URL("http://中国.icom.museum")263 assert url.raw_host == b"xn--fiqs8s.icom.museum"264265 url = httpx.URL("http://xn--fiqs8s.icom.museum")266 assert url.raw_host == b"xn--fiqs8s.icom.museum"267268 url = httpx.URL("https://[::ffff:192.168.0.1]")269 assert url.raw_host == b"::ffff:192.168.0.1"270 """271 host: str = self._uri_reference.host or ""272273 if host and ":" in host and host[0] == "[":274 # it's an IPv6 address275 host = host.lstrip("[").rstrip("]")276277 return host.encode("ascii")278279 @property280 def port(self) -> typing.Optional[int]:281 """282 The URL port as an integer.283284 Note that the URL class performs port normalization as per the WHATWG spec.285 Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always286 treated as `None`.287288 For example:289290 assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80")291 assert httpx.URL("http://www.example.com:80").port is None292 """293 port = self._uri_reference.port294 return int(port) if port else None295296 @property297 def netloc(self) -> bytes:298 """299 Either `<host>` or `<host>:<port>` as bytes.300 Always normalized to lowercase, and IDNA encoded.301302 This property may be used for generating the value of a request303 "Host" header.304 """305 host = self._uri_reference.host or ""306 port = self._uri_reference.port307 netloc = host.encode("ascii")308 if port:309 netloc = netloc + b":" + port.encode("ascii")310 return netloc311312 @property313 def path(self) -> str:314 """315 The URL path as a string. Excluding the query string, and URL decoded.316317 For example:318319 url = httpx.URL("https://example.com/pa%20th")320 assert url.path == "/pa th"321 """322 path = self._uri_reference.path or "/"323 return unquote(path)324325 @property326 def query(self) -> bytes:327 """328 The URL query string, as raw bytes, excluding the leading b"?".329330 This is necessarily a bytewise interface, because we cannot331 perform URL decoding of this representation until we've parsed332 the keys and values into a QueryParams instance.333334 For example:335336 url = httpx.URL("https://example.com/?filter=some%20search%20terms")337 assert url.query == b"filter=some%20search%20terms"338 """339 query = self._uri_reference.query or ""340 return query.encode("ascii")341342 @property343 def params(self) -> "QueryParams":344 """345 The URL query parameters, neatly parsed and packaged into an immutable346 multidict representation.347 """348 return QueryParams(self._uri_reference.query)349350 @property351 def raw_path(self) -> bytes:352 """353 The complete URL path and query string as raw bytes.354 Used as the target when constructing HTTP requests.355356 For example:357358 GET /users?search=some%20text HTTP/1.1359 Host: www.example.org360 Connection: close361 """362 path = self._uri_reference.path or "/"363 if self._uri_reference.query is not None:364 path += "?" + self._uri_reference.query365 return path.encode("ascii")366367 @property368 def fragment(self) -> str:369 """370 The URL fragments, as used in HTML anchors.371 As a string, without the leading '#'.372 """373 return unquote(self._uri_reference.fragment or "")374375 @property376 def raw(self) -> RawURL:377 """378 The URL in the raw representation used by the low level379 transport API. See `BaseTransport.handle_request`.380381 Provides the (scheme, host, port, target) for the outgoing request.382 """383 return (384 self.raw_scheme,385 self.raw_host,386 self.port,387 self.raw_path,388 )389390 @property391 def is_absolute_url(self) -> bool:392 """393 Return `True` for absolute URLs such as 'http://example.com/path',394 and `False` for relative URLs such as '/path'.395 """396 # We don't use `.is_absolute` from `rfc3986` because it treats397 # URLs with a fragment portion as not absolute.398 # What we actually care about is if the URL provides399 # a scheme and hostname to which connections should be made.400 return bool(self._uri_reference.scheme and self._uri_reference.host)401402 @property403 def is_relative_url(self) -> bool:404 """405 Return `False` for absolute URLs such as 'http://example.com/path',406 and `True` for relative URLs such as '/path'.407 """408 return not self.is_absolute_url409410 def copy_with(self, **kwargs: typing.Any) -> "URL":411 """412 Copy this URL, returning a new URL with some components altered.413 Accepts the same set of parameters as the components that are made414 available via properties on the `URL` class.415416 For example:417418 url = httpx.URL("https://www.example.com").copy_with(username="jo@gmail.com", password="a secret")419 assert url == "https://jo%40email.com:a%20secret@www.example.com"420 """421 allowed = {422 "scheme": str,423 "username": str,424 "password": str,425 "userinfo": bytes,426 "host": str,427 "port": int,428 "netloc": bytes,429 "path": str,430 "query": bytes,431 "raw_path": bytes,432 "fragment": str,433 "params": object,434 }435436 # Step 1437 # ======438 #439 # Perform type checking for all supported keyword arguments.440 for key, value in kwargs.items():441 if key not in allowed:442 message = f"{key!r} is an invalid keyword argument for copy_with()"443 raise TypeError(message)444 if value is not None and not isinstance(value, allowed[key]):445 expected = allowed[key].__name__446 seen = type(value).__name__447 message = f"Argument {key!r} must be {expected} but got {seen}"448 raise TypeError(message)449450 # Step 2451 # ======452 #453 # Consolidate "username", "password", "userinfo", "host", "port" and "netloc"454 # into a single "authority" keyword, for `rfc3986`.455 if "username" in kwargs or "password" in kwargs:456 # Consolidate "username" and "password" into "userinfo".457 username = quote(kwargs.pop("username", self.username) or "")458 password = quote(kwargs.pop("password", self.password) or "")459 userinfo = f"{username}:{password}" if password else username460 kwargs["userinfo"] = userinfo.encode("ascii")461462 if "host" in kwargs or "port" in kwargs:463 # Consolidate "host" and "port" into "netloc".464 host = kwargs.pop("host", self.host) or ""465 port = kwargs.pop("port", self.port)466467 if host and ":" in host and host[0] != "[":468 # IPv6 addresses need to be escaped within square brackets.469 host = f"[{host}]"470471 kwargs["netloc"] = (472 f"{host}:{port}".encode("ascii")473 if port is not None474 else host.encode("ascii")475 )476477 if "userinfo" in kwargs or "netloc" in kwargs:478 # Consolidate "userinfo" and "netloc" into authority.479 userinfo = (kwargs.pop("userinfo", self.userinfo) or b"").decode("ascii")480 netloc = (kwargs.pop("netloc", self.netloc) or b"").decode("ascii")481 authority = f"{userinfo}@{netloc}" if userinfo else netloc482 kwargs["authority"] = authority483484 # Step 3485 # ======486 #487 # Wrangle any "path", "query", "raw_path" and "params" keywords into488 # "query" and "path" keywords for `rfc3986`.489 if "raw_path" in kwargs:490 # If "raw_path" is included, then split it into "path" and "query" components.491 raw_path = kwargs.pop("raw_path") or b""492 path, has_query, query = raw_path.decode("ascii").partition("?")493 kwargs["path"] = path494 kwargs["query"] = query if has_query else None495496 else:497 if kwargs.get("path") is not None:498 # Ensure `kwargs["path"] = <url quoted str>` for `rfc3986`.499 kwargs["path"] = quote(kwargs["path"])500501 if kwargs.get("query") is not None:502 # Ensure `kwargs["query"] = <str>` for `rfc3986`.503 #504 # Note that `.copy_with(query=None)` and `.copy_with(query=b"")`505 # are subtly different. The `None` style will not include an empty506 # trailing "?" character.507 kwargs["query"] = kwargs["query"].decode("ascii")508509 if "params" in kwargs:510 # Replace any "params" keyword with the raw "query" instead.511 #512 # Ensure that empty params use `kwargs["query"] = None` rather513 # than `kwargs["query"] = ""`, so that generated URLs do not514 # include an empty trailing "?".515 params = kwargs.pop("params")516 kwargs["query"] = None if not params else str(QueryParams(params))517518 # Step 4519 # ======520 #521 # Ensure any fragment component is quoted.522 if kwargs.get("fragment") is not None:523 kwargs["fragment"] = quote(kwargs["fragment"])524525 # Step 5526 # ======527 #528 # At this point kwargs may include keys for "scheme", "authority", "path",529 # "query" and "fragment". Together these constitute the entire URL.530 #531 # See https://tools.ietf.org/html/rfc3986#section-3532 #533 # foo://example.com:8042/over/there?name=ferret#nose534 # \_/ \______________/\_________/ \_________/ \__/535 # | | | | |536 # scheme authority path query fragment537 return URL(self._uri_reference.copy_with(**kwargs).unsplit())538539 def copy_set_param(self, key: str, value: typing.Any = None) -> "URL":540 return self.copy_with(params=self.params.set(key, value))541542 def copy_add_param(self, key: str, value: typing.Any = None) -> "URL":543 return self.copy_with(params=self.params.add(key, value))544545 def copy_remove_param(self, key: str) -> "URL":546 return self.copy_with(params=self.params.remove(key))547548 def copy_merge_params(self, params: QueryParamTypes) -> "URL":549 return self.copy_with(params=self.params.merge(params))550551 def join(self, url: URLTypes) -> "URL":552 """553 Return an absolute URL, using this URL as the base.554555 Eg.556557 url = httpx.URL("https://www.example.com/test")558 url = url.join("/new/path")559 assert url == "https://www.example.com/new/path"560 """561 if self.is_relative_url:562 # Workaround to handle relative URLs, which otherwise raise563 # rfc3986.exceptions.ResolutionError when used as an argument564 # in `.resolve_with`.565 return (566 self.copy_with(scheme="http", host="example.com")567 .join(url)568 .copy_with(scheme=None, host=None)569 )570571 # We drop any fragment portion, because RFC 3986 strictly572 # treats URLs with a fragment portion as not being absolute URLs.573 base_uri = self._uri_reference.copy_with(fragment=None)574 relative_url = URL(url)575 return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())576577 def __hash__(self) -> int:578 return hash(str(self))579580 def __eq__(self, other: typing.Any) -> bool:581 return isinstance(other, (URL, str)) and str(self) == str(URL(other))582583 def __str__(self) -> str:584 return self._uri_reference.unsplit()585586 def __repr__(self) -> str:587 class_name = self.__class__.__name__588 url_str = str(self)589 if self._uri_reference.userinfo:590 # Mask any password component in the URL representation, to lower the591 # risk of unintended leakage, such as in debug information and logging.592 username = quote(self.username)593 url_str = (594 rfc3986.urlparse(url_str)595 .copy_with(userinfo=f"{username}:[secure]")596 .unsplit()597 )598 return f"{class_name}({url_str!r})"599600601class QueryParams(typing.Mapping[str, str]):602 """603 URL query parameters, as a multi-dict.604 """605606 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:607 assert len(args) < 2, "Too many arguments."608 assert not (args and kwargs), "Cannot mix named and unnamed arguments."609610 value = args[0] if args else kwargs611612 items: typing.Sequence[typing.Tuple[str, PrimitiveData]]613 if value is None or isinstance(value, (str, bytes)):614 value = value.decode("ascii") if isinstance(value, bytes) else value615 self._dict = parse_qs(value)616 elif isinstance(value, QueryParams):617 self._dict = {k: list(v) for k, v in value._dict.items()}618 else:619 dict_value: typing.Dict[typing.Any, typing.List[typing.Any]] = {}620 if isinstance(value, (list, tuple)):621 # Convert list inputs like:622 # [("a", "123"), ("a", "456"), ("b", "789")]623 # To a dict representation, like:624 # {"a": ["123", "456"], "b": ["789"]}625 for item in value:626 dict_value.setdefault(item[0], []).append(item[1])627 else:628 # Convert dict inputs like:629 # {"a": "123", "b": ["456", "789"]}630 # To dict inputs where values are always lists, like:631 # {"a": ["123"], "b": ["456", "789"]}632 dict_value = {633 k: list(v) if isinstance(v, (list, tuple)) else [v]634 for k, v in value.items()635 }636637 # Ensure that keys and values are neatly coerced to strings.638 # We coerce values `True` and `False` to JSON-like "true" and "false"639 # representations, and coerce `None` values to the empty string.640 self._dict = {641 str(k): [primitive_value_to_str(item) for item in v]642 for k, v in dict_value.items()643 }644645 def keys(self) -> typing.KeysView:646 """647 Return all the keys in the query params.648649 Usage:650651 q = httpx.QueryParams("a=123&a=456&b=789")652 assert list(q.keys()) == ["a", "b"]653 """654 return self._dict.keys()655656 def values(self) -> typing.ValuesView:657 """658 Return all the values in the query params. If a key occurs more than once659 only the first item for that key is returned.660661 Usage:662663 q = httpx.QueryParams("a=123&a=456&b=789")664 assert list(q.values()) == ["123", "789"]665 """666 return {k: v[0] for k, v in self._dict.items()}.values()667668 def items(self) -> typing.ItemsView:669 """670 Return all items in the query params. If a key occurs more than once671 only the first item for that key is returned.672673 Usage:674675 q = httpx.QueryParams("a=123&a=456&b=789")676 assert list(q.items()) == [("a", "123"), ("b", "789")]677 """678 return {k: v[0] for k, v in self._dict.items()}.items()679680 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:681 """682 Return all items in the query params. Allow duplicate keys to occur.683684 Usage:685686 q = httpx.QueryParams("a=123&a=456&b=789")687 assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")]688 """689 multi_items: typing.List[typing.Tuple[str, str]] = []690 for k, v in self._dict.items():691 multi_items.extend([(k, i) for i in v])692 return multi_items693694 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:695 """696 Get a value from the query param for a given key. If the key occurs697 more than once, then only the first value is returned.698699 Usage:700701 q = httpx.QueryParams("a=123&a=456&b=789")702 assert q.get("a") == "123"703 """704 if key in self._dict:705 return self._dict[str(key)][0]706 return default707708 def get_list(self, key: str) -> typing.List[str]:709 """710 Get all values from the query param for a given key.711712 Usage:713714 q = httpx.QueryParams("a=123&a=456&b=789")715 assert q.get_list("a") == ["123", "456"]716 """717 return list(self._dict.get(str(key), []))718719 def set(self, key: str, value: typing.Any = None) -> "QueryParams":720 """721 Return a new QueryParams instance, setting the value of a key.722723 Usage:724725 q = httpx.QueryParams("a=123")726 q = q.set("a", "456")727 assert q == httpx.QueryParams("a=456")728 """729 q = QueryParams()730 q._dict = dict(self._dict)731 q._dict[str(key)] = [primitive_value_to_str(value)]732 return q733734 def add(self, key: str, value: typing.Any = None) -> "QueryParams":735 """736 Return a new QueryParams instance, setting or appending the value of a key.737738 Usage:739740 q = httpx.QueryParams("a=123")741 q = q.add("a", "456")742 assert q == httpx.QueryParams("a=123&a=456")743 """744 q = QueryParams()745 q._dict = dict(self._dict)746 q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]747 return q748749 def remove(self, key: str) -> "QueryParams":750 """751 Return a new QueryParams instance, removing the value of a key.752753 Usage:754755 q = httpx.QueryParams("a=123")756 q = q.remove("a")757 assert q == httpx.QueryParams("")758 """759 q = QueryParams()760 q._dict = dict(self._dict)761 q._dict.pop(str(key), None)762 return q763764 def merge(self, params: QueryParamTypes = None) -> "QueryParams":765 """766 Return a new QueryParams instance, updated with.767768 Usage:769770 q = httpx.QueryParams("a=123")771 q = q.merge({"b": "456"})772 assert q == httpx.QueryParams("a=123&b=456")773774 q = httpx.QueryParams("a=123")775 q = q.merge({"a": "456", "b": "789"})776 assert q == httpx.QueryParams("a=456&b=789")777 """778 q = QueryParams(params)779 q._dict = {**self._dict, **q._dict}780 return q781782 def __getitem__(self, key: typing.Any) -> str:783 return self._dict[key][0]784785 def __contains__(self, key: typing.Any) -> bool:786 return key in self._dict787788 def __iter__(self) -> typing.Iterator[typing.Any]:789 return iter(self.keys())790791 def __len__(self) -> int:792 return len(self._dict)793794 def __bool__(self) -> bool:795 return bool(self._dict)796797 def __hash__(self) -> int:798 return hash(str(self))799800 def __eq__(self, other: typing.Any) -> bool:801 if not isinstance(other, self.__class__):802 return False803 return sorted(self.multi_items()) == sorted(other.multi_items())804805 def __str__(self) -> str:806 return urlencode(self.multi_items())807808 def __repr__(self) -> str:809 class_name = self.__class__.__name__810 query_string = str(self)811 return f"{class_name}({query_string!r})"812813 def update(self, params: QueryParamTypes = None) -> None:814 raise RuntimeError(815 "QueryParams are immutable since 0.18.0. "816 "Use `q = q.merge(...)` to create an updated copy."817 )818819 def __setitem__(self, key: str, value: str) -> None:820 raise RuntimeError(821 "QueryParams are immutable since 0.18.0. "822 "Use `q = q.set(key, value)` to create an updated copy."823 )82482556class Headers(typing.MutableMapping[str, str]):57 """58 HTTP headers, as a case-insensitive multi-dict.59 """
1118 unmodified lines
modified:httpx/_types.py+2 added-1 removed
22 unmodified lines
2324if TYPE_CHECKING: # pragma: no cover25 from ._auth import Auth # noqa: F40126 from ._config import Proxy, Timeout # noqa: F40127 from ._models import URL, Cookies, Headers, QueryParams, Request # noqa: F40127 from ._models import Cookies, Headers, Request # noqa: F40128 from ._urls import URL, QueryParams # noqa: F401293031PrimitiveData = Optional[Union[str, int, float, bool]]32
121 unmodified lines
added:httpx/_urls.py+773 added
1import typing2from urllib.parse import parse_qs, quote, unquote, urlencode34import idna5import rfc39866import rfc3986.exceptions78from ._exceptions import InvalidURL9from ._types import PrimitiveData, QueryParamTypes, RawURL, URLTypes10from ._utils import primitive_value_to_str111213class URL:14 """15 url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")1617 assert url.scheme == "https"18 assert url.username == "jo@email.com"19 assert url.password == "a secret"20 assert url.userinfo == b"jo%40email.com:a%20secret"21 assert url.host == "müller.de"22 assert url.raw_host == b"xn--mller-kva.de"23 assert url.port == 123424 assert url.netloc == b"xn--mller-kva.de:1234"25 assert url.path == "/pa th"26 assert url.query == b"?search=ab"27 assert url.raw_path == b"/pa%20th?search=ab"28 assert url.fragment == "anchorlink"2930 The components of a URL are broken down like this:3132 https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink33 [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment]34 [ userinfo ] [ netloc ][ raw_path ]3536 Note that:3738 * `url.scheme` is normalized to always be lowercased.3940 * `url.host` is normalized to always be lowercased. Internationalized domain41 names are represented in unicode, without IDNA encoding applied. For instance:4243 url = httpx.URL("http://中国.icom.museum")44 assert url.host == "中国.icom.museum"45 url = httpx.URL("http://xn--fiqs8s.icom.museum")46 assert url.host == "中国.icom.museum"4748 * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.4950 url = httpx.URL("http://中国.icom.museum")51 assert url.raw_host == b"xn--fiqs8s.icom.museum"52 url = httpx.URL("http://xn--fiqs8s.icom.museum")53 assert url.raw_host == b"xn--fiqs8s.icom.museum"5455 * `url.port` is either None or an integer. URLs that include the default port for56 "http", "https", "ws", "wss", and "ftp" schemes have their port normalized to `None`.5758 assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80")59 assert httpx.URL("http://example.com").port is None60 assert httpx.URL("http://example.com:80").port is None6162 * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work with63 `url.username` and `url.password` instead, which handle the URL escaping.6465 * `url.raw_path` is raw bytes of both the path and query, without URL escaping.66 This portion is used as the target when constructing HTTP requests. Usually you'll67 want to work with `url.path` instead.6869 * `url.query` is raw bytes, without URL escaping. A URL query string portion can only70 be properly URL escaped when decoding the parameter names and values themselves.71 """7273 def __init__(74 self, url: typing.Union["URL", str, RawURL] = "", **kwargs: typing.Any75 ) -> None:76 if isinstance(url, (str, tuple)):77 if isinstance(url, tuple):78 raw_scheme, raw_host, port, raw_path = url79 scheme = raw_scheme.decode("ascii")80 host = raw_host.decode("ascii")81 if host and ":" in host and host[0] != "[":82 # it's an IPv6 address, so it should be enclosed in "[" and "]"83 # ref: https://tools.ietf.org/html/rfc2732#section-284 # ref: https://tools.ietf.org/html/rfc3986#section-3.2.285 host = f"[{host}]"86 port_str = "" if port is None else f":{port}"87 path = raw_path.decode("ascii")88 url = f"{scheme}://{host}{port_str}{path}"8990 try:91 self._uri_reference = rfc3986.iri_reference(url).encode()92 except rfc3986.exceptions.InvalidAuthority as exc:93 raise InvalidURL(message=str(exc)) from None9495 if self.is_absolute_url:96 # We don't want to normalize relative URLs, since doing so97 # removes any leading `../` portion.98 self._uri_reference = self._uri_reference.normalize()99 elif isinstance(url, URL):100 self._uri_reference = url._uri_reference101 else:102 raise TypeError(103 f"Invalid type for url. Expected str or httpx.URL, got {type(url)}: {url!r}"104 )105106 # Perform port normalization, following the WHATWG spec for default ports.107 #108 # See:109 # * https://tools.ietf.org/html/rfc3986#section-3.2.3110 # * https://url.spec.whatwg.org/#url-miscellaneous111 # * https://url.spec.whatwg.org/#scheme-state112 default_port = {113 "ftp": ":21",114 "http": ":80",115 "https": ":443",116 "ws": ":80",117 "wss": ":443",118 }.get(self._uri_reference.scheme, "")119 authority = self._uri_reference.authority or ""120 if default_port and authority.endswith(default_port):121 authority = authority[: -len(default_port)]122 self._uri_reference = self._uri_reference.copy_with(authority=authority)123124 if kwargs:125 self._uri_reference = self.copy_with(**kwargs)._uri_reference126127 @property128 def scheme(self) -> str:129 """130 The URL scheme, such as "http", "https".131 Always normalised to lowercase.132 """133 return self._uri_reference.scheme or ""134135 @property136 def raw_scheme(self) -> bytes:137 """138 The raw bytes representation of the URL scheme, such as b"http", b"https".139 Always normalised to lowercase.140 """141 return self.scheme.encode("ascii")142143 @property144 def userinfo(self) -> bytes:145 """146 The URL userinfo as a raw bytestring.147 For example: b"jo%40email.com:a%20secret".148 """149 userinfo = self._uri_reference.userinfo or ""150 return userinfo.encode("ascii")151152 @property153 def username(self) -> str:154 """155 The URL username as a string, with URL decoding applied.156 For example: "jo@email.com"157 """158 userinfo = self._uri_reference.userinfo or ""159 return unquote(userinfo.partition(":")[0])160161 @property162 def password(self) -> str:163 """164 The URL password as a string, with URL decoding applied.165 For example: "a secret"166 """167 userinfo = self._uri_reference.userinfo or ""168 return unquote(userinfo.partition(":")[2])169170 @property171 def host(self) -> str:172 """173 The URL host as a string.174 Always normalized to lowercase, with IDNA hosts decoded into unicode.175176 Examples:177178 url = httpx.URL("http://www.EXAMPLE.org")179 assert url.host == "www.example.org"180181 url = httpx.URL("http://中国.icom.museum")182 assert url.host == "中国.icom.museum"183184 url = httpx.URL("http://xn--fiqs8s.icom.museum")185 assert url.host == "中国.icom.museum"186187 url = httpx.URL("https://[::ffff:192.168.0.1]")188 assert url.host == "::ffff:192.168.0.1"189 """190 host: str = self._uri_reference.host or ""191192 if host and ":" in host and host[0] == "[":193 # it's an IPv6 address194 host = host.lstrip("[").rstrip("]")195196 if host.startswith("xn--"):197 host = idna.decode(host)198199 return host200201 @property202 def raw_host(self) -> bytes:203 """204 The raw bytes representation of the URL host.205 Always normalized to lowercase, and IDNA encoded.206207 Examples:208209 url = httpx.URL("http://www.EXAMPLE.org")210 assert url.raw_host == b"www.example.org"211212 url = httpx.URL("http://中国.icom.museum")213 assert url.raw_host == b"xn--fiqs8s.icom.museum"214215 url = httpx.URL("http://xn--fiqs8s.icom.museum")216 assert url.raw_host == b"xn--fiqs8s.icom.museum"217218 url = httpx.URL("https://[::ffff:192.168.0.1]")219 assert url.raw_host == b"::ffff:192.168.0.1"220 """221 host: str = self._uri_reference.host or ""222223 if host and ":" in host and host[0] == "[":224 # it's an IPv6 address225 host = host.lstrip("[").rstrip("]")226227 return host.encode("ascii")228229 @property230 def port(self) -> typing.Optional[int]:231 """232 The URL port as an integer.233234 Note that the URL class performs port normalization as per the WHATWG spec.235 Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always236 treated as `None`.237238 For example:239240 assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80")241 assert httpx.URL("http://www.example.com:80").port is None242 """243 port = self._uri_reference.port244 return int(port) if port else None245246 @property247 def netloc(self) -> bytes:248 """249 Either `<host>` or `<host>:<port>` as bytes.250 Always normalized to lowercase, and IDNA encoded.251252 This property may be used for generating the value of a request253 "Host" header.254 """255 host = self._uri_reference.host or ""256 port = self._uri_reference.port257 netloc = host.encode("ascii")258 if port:259 netloc = netloc + b":" + port.encode("ascii")260 return netloc261262 @property263 def path(self) -> str:264 """265 The URL path as a string. Excluding the query string, and URL decoded.266267 For example:268269 url = httpx.URL("https://example.com/pa%20th")270 assert url.path == "/pa th"271 """272 path = self._uri_reference.path or "/"273 return unquote(path)274275 @property276 def query(self) -> bytes:277 """278 The URL query string, as raw bytes, excluding the leading b"?".279280 This is necessarily a bytewise interface, because we cannot281 perform URL decoding of this representation until we've parsed282 the keys and values into a QueryParams instance.283284 For example:285286 url = httpx.URL("https://example.com/?filter=some%20search%20terms")287 assert url.query == b"filter=some%20search%20terms"288 """289 query = self._uri_reference.query or ""290 return query.encode("ascii")291292 @property293 def params(self) -> "QueryParams":294 """295 The URL query parameters, neatly parsed and packaged into an immutable296 multidict representation.297 """298 return QueryParams(self._uri_reference.query)299300 @property301 def raw_path(self) -> bytes:302 """303 The complete URL path and query string as raw bytes.304 Used as the target when constructing HTTP requests.305306 For example:307308 GET /users?search=some%20text HTTP/1.1309 Host: www.example.org310 Connection: close311 """312 path = self._uri_reference.path or "/"313 if self._uri_reference.query is not None:314 path += "?" + self._uri_reference.query315 return path.encode("ascii")316317 @property318 def fragment(self) -> str:319 """320 The URL fragments, as used in HTML anchors.321 As a string, without the leading '#'.322 """323 return unquote(self._uri_reference.fragment or "")324325 @property326 def raw(self) -> RawURL:327 """328 The URL in the raw representation used by the low level329 transport API. See `BaseTransport.handle_request`.330331 Provides the (scheme, host, port, target) for the outgoing request.332 """333 return (334 self.raw_scheme,335 self.raw_host,336 self.port,337 self.raw_path,338 )339340 @property341 def is_absolute_url(self) -> bool:342 """343 Return `True` for absolute URLs such as 'http://example.com/path',344 and `False` for relative URLs such as '/path'.345 """346 # We don't use `.is_absolute` from `rfc3986` because it treats347 # URLs with a fragment portion as not absolute.348 # What we actually care about is if the URL provides349 # a scheme and hostname to which connections should be made.350 return bool(self._uri_reference.scheme and self._uri_reference.host)351352 @property353 def is_relative_url(self) -> bool:354 """355 Return `False` for absolute URLs such as 'http://example.com/path',356 and `True` for relative URLs such as '/path'.357 """358 return not self.is_absolute_url359360 def copy_with(self, **kwargs: typing.Any) -> "URL":361 """362 Copy this URL, returning a new URL with some components altered.363 Accepts the same set of parameters as the components that are made364 available via properties on the `URL` class.365366 For example:367368 url = httpx.URL("https://www.example.com").copy_with(username="jo@gmail.com", password="a secret")369 assert url == "https://jo%40email.com:a%20secret@www.example.com"370 """371 allowed = {372 "scheme": str,373 "username": str,374 "password": str,375 "userinfo": bytes,376 "host": str,377 "port": int,378 "netloc": bytes,379 "path": str,380 "query": bytes,381 "raw_path": bytes,382 "fragment": str,383 "params": object,384 }385386 # Step 1387 # ======388 #389 # Perform type checking for all supported keyword arguments.390 for key, value in kwargs.items():391 if key not in allowed:392 message = f"{key!r} is an invalid keyword argument for copy_with()"393 raise TypeError(message)394 if value is not None and not isinstance(value, allowed[key]):395 expected = allowed[key].__name__396 seen = type(value).__name__397 message = f"Argument {key!r} must be {expected} but got {seen}"398 raise TypeError(message)399400 # Step 2401 # ======402 #403 # Consolidate "username", "password", "userinfo", "host", "port" and "netloc"404 # into a single "authority" keyword, for `rfc3986`.405 if "username" in kwargs or "password" in kwargs:406 # Consolidate "username" and "password" into "userinfo".407 username = quote(kwargs.pop("username", self.username) or "")408 password = quote(kwargs.pop("password", self.password) or "")409 userinfo = f"{username}:{password}" if password else username410 kwargs["userinfo"] = userinfo.encode("ascii")411412 if "host" in kwargs or "port" in kwargs:413 # Consolidate "host" and "port" into "netloc".414 host = kwargs.pop("host", self.host) or ""415 port = kwargs.pop("port", self.port)416417 if host and ":" in host and host[0] != "[":418 # IPv6 addresses need to be escaped within square brackets.419 host = f"[{host}]"420421 kwargs["netloc"] = (422 f"{host}:{port}".encode("ascii")423 if port is not None424 else host.encode("ascii")425 )426427 if "userinfo" in kwargs or "netloc" in kwargs:428 # Consolidate "userinfo" and "netloc" into authority.429 userinfo = (kwargs.pop("userinfo", self.userinfo) or b"").decode("ascii")430 netloc = (kwargs.pop("netloc", self.netloc) or b"").decode("ascii")431 authority = f"{userinfo}@{netloc}" if userinfo else netloc432 kwargs["authority"] = authority433434 # Step 3435 # ======436 #437 # Wrangle any "path", "query", "raw_path" and "params" keywords into438 # "query" and "path" keywords for `rfc3986`.439 if "raw_path" in kwargs:440 # If "raw_path" is included, then split it into "path" and "query" components.441 raw_path = kwargs.pop("raw_path") or b""442 path, has_query, query = raw_path.decode("ascii").partition("?")443 kwargs["path"] = path444 kwargs["query"] = query if has_query else None445446 else:447 if kwargs.get("path") is not None:448 # Ensure `kwargs["path"] = <url quoted str>` for `rfc3986`.449 kwargs["path"] = quote(kwargs["path"])450451 if kwargs.get("query") is not None:452 # Ensure `kwargs["query"] = <str>` for `rfc3986`.453 #454 # Note that `.copy_with(query=None)` and `.copy_with(query=b"")`455 # are subtly different. The `None` style will not include an empty456 # trailing "?" character.457 kwargs["query"] = kwargs["query"].decode("ascii")458459 if "params" in kwargs:460 # Replace any "params" keyword with the raw "query" instead.461 #462 # Ensure that empty params use `kwargs["query"] = None` rather463 # than `kwargs["query"] = ""`, so that generated URLs do not464 # include an empty trailing "?".465 params = kwargs.pop("params")466 kwargs["query"] = None if not params else str(QueryParams(params))467468 # Step 4469 # ======470 #471 # Ensure any fragment component is quoted.472 if kwargs.get("fragment") is not None:473 kwargs["fragment"] = quote(kwargs["fragment"])474475 # Step 5476 # ======477 #478 # At this point kwargs may include keys for "scheme", "authority", "path",479 # "query" and "fragment". Together these constitute the entire URL.480 #481 # See https://tools.ietf.org/html/rfc3986#section-3482 #483 # foo://example.com:8042/over/there?name=ferret#nose484 # \_/ \______________/\_________/ \_________/ \__/485 # | | | | |486 # scheme authority path query fragment487 return URL(self._uri_reference.copy_with(**kwargs).unsplit())488489 def copy_set_param(self, key: str, value: typing.Any = None) -> "URL":490 return self.copy_with(params=self.params.set(key, value))491492 def copy_add_param(self, key: str, value: typing.Any = None) -> "URL":493 return self.copy_with(params=self.params.add(key, value))494495 def copy_remove_param(self, key: str) -> "URL":496 return self.copy_with(params=self.params.remove(key))497498 def copy_merge_params(self, params: QueryParamTypes) -> "URL":499 return self.copy_with(params=self.params.merge(params))500501 def join(self, url: URLTypes) -> "URL":502 """503 Return an absolute URL, using this URL as the base.504505 Eg.506507 url = httpx.URL("https://www.example.com/test")508 url = url.join("/new/path")509 assert url == "https://www.example.com/new/path"510 """511 if self.is_relative_url:512 # Workaround to handle relative URLs, which otherwise raise513 # rfc3986.exceptions.ResolutionError when used as an argument514 # in `.resolve_with`.515 return (516 self.copy_with(scheme="http", host="example.com")517 .join(url)518 .copy_with(scheme=None, host=None)519 )520521 # We drop any fragment portion, because RFC 3986 strictly522 # treats URLs with a fragment portion as not being absolute URLs.523 base_uri = self._uri_reference.copy_with(fragment=None)524 relative_url = URL(url)525 return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())526527 def __hash__(self) -> int:528 return hash(str(self))529530 def __eq__(self, other: typing.Any) -> bool:531 return isinstance(other, (URL, str)) and str(self) == str(URL(other))532533 def __str__(self) -> str:534 return self._uri_reference.unsplit()535536 def __repr__(self) -> str:537 class_name = self.__class__.__name__538 url_str = str(self)539 if self._uri_reference.userinfo:540 # Mask any password component in the URL representation, to lower the541 # risk of unintended leakage, such as in debug information and logging.542 username = quote(self.username)543 url_str = (544 rfc3986.urlparse(url_str)545 .copy_with(userinfo=f"{username}:[secure]")546 .unsplit()547 )548 return f"{class_name}({url_str!r})"549550551class QueryParams(typing.Mapping[str, str]):552 """553 URL query parameters, as a multi-dict.554 """555556 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:557 assert len(args) < 2, "Too many arguments."558 assert not (args and kwargs), "Cannot mix named and unnamed arguments."559560 value = args[0] if args else kwargs561562 items: typing.Sequence[typing.Tuple[str, PrimitiveData]]563 if value is None or isinstance(value, (str, bytes)):564 value = value.decode("ascii") if isinstance(value, bytes) else value565 self._dict = parse_qs(value)566 elif isinstance(value, QueryParams):567 self._dict = {k: list(v) for k, v in value._dict.items()}568 else:569 dict_value: typing.Dict[typing.Any, typing.List[typing.Any]] = {}570 if isinstance(value, (list, tuple)):571 # Convert list inputs like:572 # [("a", "123"), ("a", "456"), ("b", "789")]573 # To a dict representation, like:574 # {"a": ["123", "456"], "b": ["789"]}575 for item in value:576 dict_value.setdefault(item[0], []).append(item[1])577 else:578 # Convert dict inputs like:579 # {"a": "123", "b": ["456", "789"]}580 # To dict inputs where values are always lists, like:581 # {"a": ["123"], "b": ["456", "789"]}582 dict_value = {583 k: list(v) if isinstance(v, (list, tuple)) else [v]584 for k, v in value.items()585 }586587 # Ensure that keys and values are neatly coerced to strings.588 # We coerce values `True` and `False` to JSON-like "true" and "false"589 # representations, and coerce `None` values to the empty string.590 self._dict = {591 str(k): [primitive_value_to_str(item) for item in v]592 for k, v in dict_value.items()593 }594595 def keys(self) -> typing.KeysView:596 """597 Return all the keys in the query params.598599 Usage:600601 q = httpx.QueryParams("a=123&a=456&b=789")602 assert list(q.keys()) == ["a", "b"]603 """604 return self._dict.keys()605606 def values(self) -> typing.ValuesView:607 """608 Return all the values in the query params. If a key occurs more than once609 only the first item for that key is returned.610611 Usage:612613 q = httpx.QueryParams("a=123&a=456&b=789")614 assert list(q.values()) == ["123", "789"]615 """616 return {k: v[0] for k, v in self._dict.items()}.values()617618 def items(self) -> typing.ItemsView:619 """620 Return all items in the query params. If a key occurs more than once621 only the first item for that key is returned.622623 Usage:624625 q = httpx.QueryParams("a=123&a=456&b=789")626 assert list(q.items()) == [("a", "123"), ("b", "789")]627 """628 return {k: v[0] for k, v in self._dict.items()}.items()629630 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:631 """632 Return all items in the query params. Allow duplicate keys to occur.633634 Usage:635636 q = httpx.QueryParams("a=123&a=456&b=789")637 assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")]638 """639 multi_items: typing.List[typing.Tuple[str, str]] = []640 for k, v in self._dict.items():641 multi_items.extend([(k, i) for i in v])642 return multi_items643644 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:645 """646 Get a value from the query param for a given key. If the key occurs647 more than once, then only the first value is returned.648649 Usage:650651 q = httpx.QueryParams("a=123&a=456&b=789")652 assert q.get("a") == "123"653 """654 if key in self._dict:655 return self._dict[str(key)][0]656 return default657658 def get_list(self, key: str) -> typing.List[str]:659 """660 Get all values from the query param for a given key.661662 Usage:663664 q = httpx.QueryParams("a=123&a=456&b=789")665 assert q.get_list("a") == ["123", "456"]666 """667 return list(self._dict.get(str(key), []))668669 def set(self, key: str, value: typing.Any = None) -> "QueryParams":670 """671 Return a new QueryParams instance, setting the value of a key.672673 Usage:674675 q = httpx.QueryParams("a=123")676 q = q.set("a", "456")677 assert q == httpx.QueryParams("a=456")678 """679 q = QueryParams()680 q._dict = dict(self._dict)681 q._dict[str(key)] = [primitive_value_to_str(value)]682 return q683684 def add(self, key: str, value: typing.Any = None) -> "QueryParams":685 """686 Return a new QueryParams instance, setting or appending the value of a key.687688 Usage:689690 q = httpx.QueryParams("a=123")691 q = q.add("a", "456")692 assert q == httpx.QueryParams("a=123&a=456")693 """694 q = QueryParams()695 q._dict = dict(self._dict)696 q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]697 return q698699 def remove(self, key: str) -> "QueryParams":700 """701 Return a new QueryParams instance, removing the value of a key.702703 Usage:704705 q = httpx.QueryParams("a=123")706 q = q.remove("a")707 assert q == httpx.QueryParams("")708 """709 q = QueryParams()710 q._dict = dict(self._dict)711 q._dict.pop(str(key), None)712 return q713714 def merge(self, params: QueryParamTypes = None) -> "QueryParams":715 """716 Return a new QueryParams instance, updated with.717718 Usage:719720 q = httpx.QueryParams("a=123")721 q = q.merge({"b": "456"})722 assert q == httpx.QueryParams("a=123&b=456")723724 q = httpx.QueryParams("a=123")725 q = q.merge({"a": "456", "b": "789"})726 assert q == httpx.QueryParams("a=456&b=789")727 """728 q = QueryParams(params)729 q._dict = {**self._dict, **q._dict}730 return q731732 def __getitem__(self, key: typing.Any) -> str:733 return self._dict[key][0]734735 def __contains__(self, key: typing.Any) -> bool:736 return key in self._dict737738 def __iter__(self) -> typing.Iterator[typing.Any]:739 return iter(self.keys())740741 def __len__(self) -> int:742 return len(self._dict)743744 def __bool__(self) -> bool:745 return bool(self._dict)746747 def __hash__(self) -> int:748 return hash(str(self))749750 def __eq__(self, other: typing.Any) -> bool:751 if not isinstance(other, self.__class__):752 return False753 return sorted(self.multi_items()) == sorted(other.multi_items())754755 def __str__(self) -> str:756 return urlencode(self.multi_items())757758 def __repr__(self) -> str:759 class_name = self.__class__.__name__760 query_string = str(self)761 return f"{class_name}({query_string!r})"762763 def update(self, params: QueryParamTypes = None) -> None:764 raise RuntimeError(765 "QueryParams are immutable since 0.18.0. "766 "Use `q = q.merge(...)` to create an updated copy."767 )768769 def __setitem__(self, key: str, value: str) -> None:770 raise RuntimeError(771 "QueryParams are immutable since 0.18.0. "772 "Use `q = q.set(key, value)` to create an updated copy."773 )