Expand URL interface (#1601)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Expand URL interface * Add URL query param manipulation methods
authored by Tom Christie · committed by GitHub · parent 2abb2f2 · Browse files · 2 files·+83 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+83 added−18 removed
- tests:+35 added−1 removed
- other:+48 added−17 removed
Provenance
- Commit
e67b0dd- Tree
51ea336- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2abb2f2
2 files changed+83 added−18 removed
modified:httpx/_models.py+48 added-17 removed
110 unmodified lines111 be properly URL escaped when decoding the parameter names and values themselves.112 """113 114 def __init__(115- self, url: typing.Union["URL", str, RawURL] = "", params: QueryParamTypes = None115+ self, url: typing.Union["URL", str, RawURL] = "", **kwargs: typing.Any116 ) -> None:117 if isinstance(url, (str, tuple)):118 if isinstance(url, tuple):119 raw_scheme, raw_host, port, raw_path = url23 unmodified lines143 raise TypeError(144 f"Invalid type for url. Expected str or httpx.URL, got {type(url)}: {url!r}"145 )146 147- # Add any query parameters, merging with any in the URL if needed.148- if params:149- if self._uri_reference.query:150- url_params = QueryParams(self._uri_reference.query).merge(params)151- query_string = str(url_params)152- else:153- query_string = str(QueryParams(params))154- self._uri_reference = self._uri_reference.copy_with(query=query_string)147+ if kwargs:148+ self._uri_reference = self.copy_with(**kwargs)._uri_reference149 150 @property151 def scheme(self) -> str:152 """133 unmodified lines286 @property287 def query(self) -> bytes:288 """289 The URL query string, as raw bytes, excluding the leading b"?".296- Note that URL decoding can only be applied on URL query strings297- at the point of decoding the individual parameter names/values.290+291+ This is neccessarily a bytewise interface, because we cannot292+ perform URL decoding of this representation until we've parsed293+ the keys and values into a QueryParams instance.294+295+ For example:296+297+ url = httpx.URL("https://example.com/?filter=some%20search%20terms")298+ assert url.query == b"filter=some%20search%20terms"299 """300 query = self._uri_reference.query or ""301 return query.encode("ascii")302 303 @property304+ def params(self) -> "QueryParams":305+ """306+ The URL query parameters, neatly parsed and packaged into an immutable307+ multidict representation.308+ """309+ return QueryParams(self._uri_reference.query)310+311+ @property312 def raw_path(self) -> bytes:313 """314 The complete URL path and query string as raw bytes.315 Used as the target when constructing HTTP requests.74 unmodified lines390 "path": str,391 "query": bytes,392 "raw_path": bytes,393 "fragment": str,394+ "params": object,395 }396 for key, value in kwargs.items():397 if key not in allowed:398 message = f"{key!r} is an invalid keyword argument for copy_with()"44 unmodified lines443 # Ensure path=<url quoted str> for rfc3986444 if kwargs.get("path") is not None:445 kwargs["path"] = quote(kwargs["path"])446 437- # Ensure query=<str> for rfc3986447 if kwargs.get("query") is not None:448+ # Ensure query=<str> for rfc3986449 kwargs["query"] = kwargs["query"].decode("ascii")450 451+ if "params" in kwargs:452+ params = kwargs.pop("params")453+ kwargs["query"] = None if not params else str(QueryParams(params))454+455 return URL(self._uri_reference.copy_with(**kwargs).unsplit())456 457+ def copy_set_param(self, key: str, value: typing.Any = None) -> "URL":458+ return self.copy_with(params=self.params.set(key, value))459+460+ def copy_add_param(self, key: str, value: typing.Any = None) -> "URL":461+ return self.copy_with(params=self.params.add(key, value))462+463+ def copy_remove_param(self, key: str) -> "URL":464+ return self.copy_with(params=self.params.remove(key))465+466+ def copy_merge_params(self, params: QueryParamTypes) -> "URL":467+ return self.copy_with(params=self.params.merge(params))468+469 def join(self, url: URLTypes) -> "URL":470 """471 Return an absolute URL, using this URL as the base.472 147 unmodified lines620 if key in self._dict:621 return self._dict[str(key)][0]622 return default623 598- def get_list(self, key: typing.Any) -> typing.List[str]:624+ def get_list(self, key: str) -> typing.List[str]:625 """626 Get all values from the query param for a given key.627 628 Usage:2 unmodified lines631 assert q.get_list("a") == ["123", "456"]632 """633 return list(self._dict.get(str(key), []))634 609- def set(self, key: typing.Any, value: typing.Any = None) -> "QueryParams":635+ def set(self, key: str, value: typing.Any = None) -> "QueryParams":636 """637 Return a new QueryParams instance, setting the value of a key.638 639 Usage:6 unmodified lines646 q._dict = dict(self._dict)647 q._dict[str(key)] = [primitive_value_to_str(value)]648 return q649 624- def add(self, key: typing.Any, value: typing.Any = None) -> "QueryParams":650+ def add(self, key: str, value: typing.Any = None) -> "QueryParams":651 """652 Return a new QueryParams instance, setting or appending the value of a key.653 654 Usage:6 unmodified lines661 q._dict = dict(self._dict)662 q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]663 return q664 639- def remove(self, key: typing.Any) -> "QueryParams":665+ def remove(self, key: str) -> "QueryParams":666 """667 Return a new QueryParams instance, removing the value of a key.668 669 Usage:36 unmodified lines706 707 def __len__(self) -> int:708 return len(self._dict)709 710+ def __bool__(self) -> bool:711+ return bool(self._dict)712+713 def __hash__(self) -> int:714 return hash(str(self))715 716 def __eq__(self, other: typing.Any) -> bool:282 unmodified lines999 if isinstance(method, bytes):1000 self.method = method.decode("ascii").upper()1001 else:1002 self.method = method.upper()974- self.url = URL(url, params=params)1003+ self.url = URL(url)1004+ if params is not None:1005+ self.url = self.url.copy_merge_params(params=params)1006 self.headers = Headers(headers)1007 if cookies:1008 Cookies(cookies).set_cookie_header(self)1009 757 unmodified linesmodified:tests/models/test_url.py+35 added-1 removed
98 unmodified lines99 100 def test_url_params():101 url = httpx.URL("https://example.org:123/path/to/somewhere", params={"a": "123"})102 assert str(url) == "https://example.org:123/path/to/somewhere?a=123"103+ assert url.params == httpx.QueryParams({"a": "123"})104 105 url = httpx.URL(106 "https://example.org:123/path/to/somewhere?b=456", params={"a": "123"}107 )107- assert str(url) == "https://example.org:123/path/to/somewhere?b=456&a=123"108+ assert str(url) == "https://example.org:123/path/to/somewhere?a=123"109+ assert url.params == httpx.QueryParams({"a": "123"})110 111 112 def test_url_join():113 """9 unmodified lines123 )124 assert url.join("../../somewhere-else") == "https://example.org:123/somewhere-else"125 126 127+def test_url_set_param_manipulation():128+ """129+ Some basic URL query parameter manipulation.130+ """131+ url = httpx.URL("https://example.org:123/?a=123")132+ assert url.copy_set_param("a", "456") == "https://example.org:123/?a=456"133+134+135+def test_url_add_param_manipulation():136+ """137+ Some basic URL query parameter manipulation.138+ """139+ url = httpx.URL("https://example.org:123/?a=123")140+ assert url.copy_add_param("a", "456") == "https://example.org:123/?a=123&a=456"141+142+143+def test_url_remove_param_manipulation():144+ """145+ Some basic URL query parameter manipulation.146+ """147+ url = httpx.URL("https://example.org:123/?a=123")148+ assert url.copy_remove_param("a") == "https://example.org:123/"149+150+151+def test_url_merge_params_manipulation():152+ """153+ Some basic URL query parameter manipulation.154+ """155+ url = httpx.URL("https://example.org:123/?a=123")156+ assert url.copy_merge_params({"b": "456"}) == "https://example.org:123/?a=123&b=456"157+158+159 def test_relative_url_join():160 url = httpx.URL("/path/to/somewhere")161 assert url.join("/somewhere-else") == "/somewhere-else"162 assert url.join("somewhere-else") == "/path/to/somewhere-else"216 unmodified lines