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
Provenance
- Commit
d07c4b4- Tree
e694d16- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2072aa2
5 files changed+780 added−774 removed
modified:httpx/__init__.py+2 added-1 removed
32 unmodified lines33 UnsupportedProtocol,34 WriteError,35 WriteTimeout,36 )37-from ._models import URL, Cookies, Headers, QueryParams, Request, Response37+from ._models import Cookies, Headers, Request, Response38 from ._status_codes import codes39 from ._transports.asgi import ASGITransport40 from ._transports.base import AsyncBaseTransport, BaseTransport41 from ._transports.default import AsyncHTTPTransport, HTTPTransport42 from ._transports.mock import MockTransport43 from ._transports.wsgi import WSGITransport44 from ._types import AsyncByteStream, SyncByteStream45+from ._urls import URL, QueryParams46 47 try:48 from ._main import main49 except ImportError: # pragma: nocover88 unmodified linesmodified:httpx/_client.py+2 added-1 removed
21 unmodified lines22 RemoteProtocolError,23 TooManyRedirects,24 request_context,25 )26-from ._models import URL, Cookies, Headers, QueryParams, Request, Response26+from ._models import Cookies, Headers, Request, Response27 from ._status_codes import codes28 from ._transports.asgi import ASGITransport29 from ._transports.base import AsyncBaseTransport, BaseTransport30 from ._transports.default import AsyncHTTPTransport, HTTPTransport13 unmodified lines44 TimeoutTypes,45 URLTypes,46 VerifyTypes,47 )48+from ._urls import URL, QueryParams49 from ._utils import (50 NetRCInfo,51 Timer,52 URLPattern,1929 unmodified linesmodified:httpx/_models.py+1 added-771 removed
4 unmodified lines5 import typing6 import urllib.request7 from collections.abc import MutableMapping8 from http.cookiejar import Cookie, CookieJar9-from urllib.parse import parse_qs, quote, unquote, urlencode9 10 import charset_normalizer12-import idna13-import rfc398614-import rfc3986.exceptions11 12 from ._content import ByteStream, UnattachedStream, encode_request, encode_response13 from ._decoders import (14 SUPPORTED_DECODERS,7 unmodified lines22 )23 from ._exceptions import (24 CookieConflict,25 HTTPStatusError,30- InvalidURL,26 RequestNotRead,27 ResponseNotRead,28 StreamClosed,29 StreamConsumed,3 unmodified lines33 from ._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 )45+from ._urls import URL46 from ._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 )54 55 63-class URL:64- """65- url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")66-67- 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"79-80- The components of a URL are broken down like this:81-82- 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 ]85-86- Note that:87-88- * `url.scheme` is normalized to always be lowercased.89-90- * `url.host` is normalized to always be lowercased. Internationalized domain91- names are represented in unicode, without IDNA encoding applied. For instance:92-93- 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"97-98- * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.99-100- 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"104-105- * `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`.107-108- 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 None111-112- * `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.114-115- * `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.118-119- * `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- """122-123- 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}"139-140- try:141- self._uri_reference = rfc3986.iri_reference(url).encode()142- except rfc3986.exceptions.InvalidAuthority as exc:143- raise InvalidURL(message=str(exc)) from None144-145- 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- )155-156- # 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)173-174- if kwargs:175- self._uri_reference = self.copy_with(**kwargs)._uri_reference176-177- @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 ""184-185- @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")192-193- @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")201-202- @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])210-211- @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])219-220- @property221- def host(self) -> str:222- """223- The URL host as a string.224- Always normalized to lowercase, with IDNA hosts decoded into unicode.225-226- Examples:227-228- url = httpx.URL("http://www.EXAMPLE.org")229- assert url.host == "www.example.org"230-231- url = httpx.URL("http://中国.icom.museum")232- assert url.host == "中国.icom.museum"233-234- url = httpx.URL("http://xn--fiqs8s.icom.museum")235- assert url.host == "中国.icom.museum"236-237- 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 ""241-242- if host and ":" in host and host[0] == "[":243- # it's an IPv6 address244- host = host.lstrip("[").rstrip("]")245-246- if host.startswith("xn--"):247- host = idna.decode(host)248-249- return host250-251- @property252- def raw_host(self) -> bytes:253- """254- The raw bytes representation of the URL host.255- Always normalized to lowercase, and IDNA encoded.256-257- Examples:258-259- url = httpx.URL("http://www.EXAMPLE.org")260- assert url.raw_host == b"www.example.org"261-262- url = httpx.URL("http://中国.icom.museum")263- assert url.raw_host == b"xn--fiqs8s.icom.museum"264-265- url = httpx.URL("http://xn--fiqs8s.icom.museum")266- assert url.raw_host == b"xn--fiqs8s.icom.museum"267-268- 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 ""272-273- if host and ":" in host and host[0] == "[":274- # it's an IPv6 address275- host = host.lstrip("[").rstrip("]")276-277- return host.encode("ascii")278-279- @property280- def port(self) -> typing.Optional[int]:281- """282- The URL port as an integer.283-284- 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`.287-288- For example:289-290- 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 None295-296- @property297- def netloc(self) -> bytes:298- """299- Either `<host>` or `<host>:<port>` as bytes.300- Always normalized to lowercase, and IDNA encoded.301-302- 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 netloc311-312- @property313- def path(self) -> str:314- """315- The URL path as a string. Excluding the query string, and URL decoded.316-317- For example:318-319- 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)324-325- @property326- def query(self) -> bytes:327- """328- The URL query string, as raw bytes, excluding the leading b"?".329-330- 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.333-334- For example:335-336- 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")341-342- @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)349-350- @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.355-356- For example:357-358- 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")366-367- @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 "")374-375- @property376- def raw(self) -> RawURL:377- """378- The URL in the raw representation used by the low level379- transport API. See `BaseTransport.handle_request`.380-381- 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- )389-390- @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)401-402- @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_url409-410- 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.415-416- For example:417-418- 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- }435-436- # 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)449-450- # 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")461-462- 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)466-467- if host and ":" in host and host[0] != "[":468- # IPv6 addresses need to be escaped within square brackets.469- host = f"[{host}]"470-471- kwargs["netloc"] = (472- f"{host}:{port}".encode("ascii")473- if port is not None474- else host.encode("ascii")475- )476-477- 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"] = authority483-484- # 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 None495-496- else:497- if kwargs.get("path") is not None:498- # Ensure `kwargs["path"] = <url quoted str>` for `rfc3986`.499- kwargs["path"] = quote(kwargs["path"])500-501- 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")508-509- 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))517-518- # Step 4519- # ======520- #521- # Ensure any fragment component is quoted.522- if kwargs.get("fragment") is not None:523- kwargs["fragment"] = quote(kwargs["fragment"])524-525- # 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())538-539- def copy_set_param(self, key: str, value: typing.Any = None) -> "URL":540- return self.copy_with(params=self.params.set(key, value))541-542- def copy_add_param(self, key: str, value: typing.Any = None) -> "URL":543- return self.copy_with(params=self.params.add(key, value))544-545- def copy_remove_param(self, key: str) -> "URL":546- return self.copy_with(params=self.params.remove(key))547-548- def copy_merge_params(self, params: QueryParamTypes) -> "URL":549- return self.copy_with(params=self.params.merge(params))550-551- def join(self, url: URLTypes) -> "URL":552- """553- Return an absolute URL, using this URL as the base.554-555- Eg.556-557- 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- )570-571- # 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())576-577- def __hash__(self) -> int:578- return hash(str(self))579-580- def __eq__(self, other: typing.Any) -> bool:581- return isinstance(other, (URL, str)) and str(self) == str(URL(other))582-583- def __str__(self) -> str:584- return self._uri_reference.unsplit()585-586- 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})"599-600-601-class QueryParams(typing.Mapping[str, str]):602- """603- URL query parameters, as a multi-dict.604- """605-606- 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."609-610- value = args[0] if args else kwargs611-612- 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- }636-637- # 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- }644-645- def keys(self) -> typing.KeysView:646- """647- Return all the keys in the query params.648-649- Usage:650-651- q = httpx.QueryParams("a=123&a=456&b=789")652- assert list(q.keys()) == ["a", "b"]653- """654- return self._dict.keys()655-656- 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.660-661- Usage:662-663- 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()667-668- 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.672-673- Usage:674-675- 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()679-680- def multi_items(self) -> typing.List[typing.Tuple[str, str]]:681- """682- Return all items in the query params. Allow duplicate keys to occur.683-684- Usage:685-686- 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_items693-694- 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.698-699- Usage:700-701- 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 default707-708- def get_list(self, key: str) -> typing.List[str]:709- """710- Get all values from the query param for a given key.711-712- Usage:713-714- 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), []))718-719- def set(self, key: str, value: typing.Any = None) -> "QueryParams":720- """721- Return a new QueryParams instance, setting the value of a key.722-723- Usage:724-725- 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 q733-734- 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.737-738- Usage:739-740- 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 q748-749- def remove(self, key: str) -> "QueryParams":750- """751- Return a new QueryParams instance, removing the value of a key.752-753- Usage:754-755- 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 q763-764- def merge(self, params: QueryParamTypes = None) -> "QueryParams":765- """766- Return a new QueryParams instance, updated with.767-768- Usage:769-770- q = httpx.QueryParams("a=123")771- q = q.merge({"b": "456"})772- assert q == httpx.QueryParams("a=123&b=456")773-774- 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 q781-782- def __getitem__(self, key: typing.Any) -> str:783- return self._dict[key][0]784-785- def __contains__(self, key: typing.Any) -> bool:786- return key in self._dict787-788- def __iter__(self) -> typing.Iterator[typing.Any]:789- return iter(self.keys())790-791- def __len__(self) -> int:792- return len(self._dict)793-794- def __bool__(self) -> bool:795- return bool(self._dict)796-797- def __hash__(self) -> int:798- return hash(str(self))799-800- 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())804-805- def __str__(self) -> str:806- return urlencode(self.multi_items())807-808- def __repr__(self) -> str:809- class_name = self.__class__.__name__810- query_string = str(self)811- return f"{class_name}({query_string!r})"812-813- 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- )818-819- 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- )824-825-56 class Headers(typing.MutableMapping[str, str]):57 """58 HTTP headers, as a case-insensitive multi-dict.59 """1118 unmodified linesmodified:httpx/_types.py+2 added-1 removed
22 unmodified lines23 24 if 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: F40129 30 31 PrimitiveData = Optional[Union[str, int, float, bool]]32 121 unmodified linesadded:httpx/_urls.py+773 added
1+import typing2+from urllib.parse import parse_qs, quote, unquote, urlencode3+4+import idna5+import rfc39866+import rfc3986.exceptions7+8+from ._exceptions import InvalidURL9+from ._types import PrimitiveData, QueryParamTypes, RawURL, URLTypes10+from ._utils import primitive_value_to_str11+12+13+class URL:14+ """15+ url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")16+17+ 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"29+30+ The components of a URL are broken down like this:31+32+ 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 ]35+36+ Note that:37+38+ * `url.scheme` is normalized to always be lowercased.39+40+ * `url.host` is normalized to always be lowercased. Internationalized domain41+ names are represented in unicode, without IDNA encoding applied. For instance:42+43+ 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"47+48+ * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.49+50+ 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"54+55+ * `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`.57+58+ 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 None61+62+ * `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.64+65+ * `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.68+69+ * `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+ """72+73+ 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}"89+90+ try:91+ self._uri_reference = rfc3986.iri_reference(url).encode()92+ except rfc3986.exceptions.InvalidAuthority as exc:93+ raise InvalidURL(message=str(exc)) from None94+95+ 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+ )105+106+ # 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)123+124+ if kwargs:125+ self._uri_reference = self.copy_with(**kwargs)._uri_reference126+127+ @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 ""134+135+ @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")142+143+ @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")151+152+ @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])160+161+ @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])169+170+ @property171+ def host(self) -> str:172+ """173+ The URL host as a string.174+ Always normalized to lowercase, with IDNA hosts decoded into unicode.175+176+ Examples:177+178+ url = httpx.URL("http://www.EXAMPLE.org")179+ assert url.host == "www.example.org"180+181+ url = httpx.URL("http://中国.icom.museum")182+ assert url.host == "中国.icom.museum"183+184+ url = httpx.URL("http://xn--fiqs8s.icom.museum")185+ assert url.host == "中国.icom.museum"186+187+ 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 ""191+192+ if host and ":" in host and host[0] == "[":193+ # it's an IPv6 address194+ host = host.lstrip("[").rstrip("]")195+196+ if host.startswith("xn--"):197+ host = idna.decode(host)198+199+ return host200+201+ @property202+ def raw_host(self) -> bytes:203+ """204+ The raw bytes representation of the URL host.205+ Always normalized to lowercase, and IDNA encoded.206+207+ Examples:208+209+ url = httpx.URL("http://www.EXAMPLE.org")210+ assert url.raw_host == b"www.example.org"211+212+ url = httpx.URL("http://中国.icom.museum")213+ assert url.raw_host == b"xn--fiqs8s.icom.museum"214+215+ url = httpx.URL("http://xn--fiqs8s.icom.museum")216+ assert url.raw_host == b"xn--fiqs8s.icom.museum"217+218+ 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 ""222+223+ if host and ":" in host and host[0] == "[":224+ # it's an IPv6 address225+ host = host.lstrip("[").rstrip("]")226+227+ return host.encode("ascii")228+229+ @property230+ def port(self) -> typing.Optional[int]:231+ """232+ The URL port as an integer.233+234+ 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`.237+238+ For example:239+240+ 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 None245+246+ @property247+ def netloc(self) -> bytes:248+ """249+ Either `<host>` or `<host>:<port>` as bytes.250+ Always normalized to lowercase, and IDNA encoded.251+252+ 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 netloc261+262+ @property263+ def path(self) -> str:264+ """265+ The URL path as a string. Excluding the query string, and URL decoded.266+267+ For example:268+269+ 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)274+275+ @property276+ def query(self) -> bytes:277+ """278+ The URL query string, as raw bytes, excluding the leading b"?".279+280+ 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.283+284+ For example:285+286+ 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")291+292+ @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)299+300+ @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.305+306+ For example:307+308+ 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")316+317+ @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 "")324+325+ @property326+ def raw(self) -> RawURL:327+ """328+ The URL in the raw representation used by the low level329+ transport API. See `BaseTransport.handle_request`.330+331+ 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+ )339+340+ @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)351+352+ @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_url359+360+ 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.365+366+ For example:367+368+ 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+ }385+386+ # 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)399+400+ # 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")411+412+ 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)416+417+ if host and ":" in host and host[0] != "[":418+ # IPv6 addresses need to be escaped within square brackets.419+ host = f"[{host}]"420+421+ kwargs["netloc"] = (422+ f"{host}:{port}".encode("ascii")423+ if port is not None424+ else host.encode("ascii")425+ )426+427+ 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"] = authority433+434+ # 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 None445+446+ else:447+ if kwargs.get("path") is not None:448+ # Ensure `kwargs["path"] = <url quoted str>` for `rfc3986`.449+ kwargs["path"] = quote(kwargs["path"])450+451+ 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")458+459+ 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))467+468+ # Step 4469+ # ======470+ #471+ # Ensure any fragment component is quoted.472+ if kwargs.get("fragment") is not None:473+ kwargs["fragment"] = quote(kwargs["fragment"])474+475+ # 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())488+489+ def copy_set_param(self, key: str, value: typing.Any = None) -> "URL":490+ return self.copy_with(params=self.params.set(key, value))491+492+ def copy_add_param(self, key: str, value: typing.Any = None) -> "URL":493+ return self.copy_with(params=self.params.add(key, value))494+495+ def copy_remove_param(self, key: str) -> "URL":496+ return self.copy_with(params=self.params.remove(key))497+498+ def copy_merge_params(self, params: QueryParamTypes) -> "URL":499+ return self.copy_with(params=self.params.merge(params))500+501+ def join(self, url: URLTypes) -> "URL":502+ """503+ Return an absolute URL, using this URL as the base.504+505+ Eg.506+507+ 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+ )520+521+ # 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())526+527+ def __hash__(self) -> int:528+ return hash(str(self))529+530+ def __eq__(self, other: typing.Any) -> bool:531+ return isinstance(other, (URL, str)) and str(self) == str(URL(other))532+533+ def __str__(self) -> str:534+ return self._uri_reference.unsplit()535+536+ 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})"549+550+551+class QueryParams(typing.Mapping[str, str]):552+ """553+ URL query parameters, as a multi-dict.554+ """555+556+ 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."559+560+ value = args[0] if args else kwargs561+562+ 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+ }586+587+ # 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+ }594+595+ def keys(self) -> typing.KeysView:596+ """597+ Return all the keys in the query params.598+599+ Usage:600+601+ q = httpx.QueryParams("a=123&a=456&b=789")602+ assert list(q.keys()) == ["a", "b"]603+ """604+ return self._dict.keys()605+606+ 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.610+611+ Usage:612+613+ 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()617+618+ 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.622+623+ Usage:624+625+ 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()629+630+ def multi_items(self) -> typing.List[typing.Tuple[str, str]]:631+ """632+ Return all items in the query params. Allow duplicate keys to occur.633+634+ Usage:635+636+ 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_items643+644+ 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.648+649+ Usage:650+651+ 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 default657+658+ def get_list(self, key: str) -> typing.List[str]:659+ """660+ Get all values from the query param for a given key.661+662+ Usage:663+664+ 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), []))668+669+ def set(self, key: str, value: typing.Any = None) -> "QueryParams":670+ """671+ Return a new QueryParams instance, setting the value of a key.672+673+ Usage:674+675+ 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 q683+684+ 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.687+688+ Usage:689+690+ 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 q698+699+ def remove(self, key: str) -> "QueryParams":700+ """701+ Return a new QueryParams instance, removing the value of a key.702+703+ Usage:704+705+ 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 q713+714+ def merge(self, params: QueryParamTypes = None) -> "QueryParams":715+ """716+ Return a new QueryParams instance, updated with.717+718+ Usage:719+720+ q = httpx.QueryParams("a=123")721+ q = q.merge({"b": "456"})722+ assert q == httpx.QueryParams("a=123&b=456")723+724+ 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 q731+732+ def __getitem__(self, key: typing.Any) -> str:733+ return self._dict[key][0]734+735+ def __contains__(self, key: typing.Any) -> bool:736+ return key in self._dict737+738+ def __iter__(self) -> typing.Iterator[typing.Any]:739+ return iter(self.keys())740+741+ def __len__(self) -> int:742+ return len(self._dict)743+744+ def __bool__(self) -> bool:745+ return bool(self._dict)746+747+ def __hash__(self) -> int:748+ return hash(str(self))749+750+ 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())754+755+ def __str__(self) -> str:756+ return urlencode(self.multi_items())757+758+ def __repr__(self) -> str:759+ class_name = self.__class__.__name__760+ query_string = str(self)761+ return f"{class_name}({query_string!r})"762+763+ 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+ )768+769+ 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+ )