Review urlescape percent-safe set, and use + behavior for form spaces. (#3373)
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 d293374 · Browse files · 3 files·+28 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+28 added−47 removed
- tests:+8 added−12 removed
- other:+20 added−35 removed
Provenance
- Commit
ba2e512- Tree
a832a93- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
d293374
3 files changed+28 added−47 removed
modified:httpx/_urlparse.py+3 added-25 removed
95 unmodified lines96 + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)97 ]98 )99 100+101 # {scheme}: (optional)102 # //{authority} (optional)103 # {path}104 # ?{query} (optional)373 unmodified lines478 def PERCENT(string: str) -> str:479 return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")])480 481 481-def percent_encoded(string: str, safe: str = "/") -> str:482+def percent_encoded(string: str, safe: str) -> str:483 """484 Use percent-encoding to quote a string.485 """486 NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe6 unmodified lines493 [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string]494 )495 496 496-def quote(string: str, safe: str = "/") -> str:497+def quote(string: str, safe: str) -> str:498 """499 Use percent-encoding to quote a string, omitting existing '%xx' escape sequences.500 501 See: https://www.rfc-editor.org/rfc/rfc3986#section-2.122 unmodified lines524 trailing_text = string[current_position:]525 parts.append(percent_encoded(trailing_text, safe=safe))526 527 return "".join(parts)527-528-529-def urlencode(items: list[tuple[str, str]]) -> str:530- """531- We can use a much simpler version of the stdlib urlencode here because532- we don't need to handle a bunch of different typing cases, such as bytes vs str.533-534- https://github.com/python/cpython/blob/b2f7b2ef0b5421e01efb8c7bee2ef95d3bab77eb/Lib/urllib/parse.py#L926535-536- Note that we use '%20' encoding for spaces. and '%2F for '/'.537- This is slightly different than `requests`, but is the behaviour that browsers use.538-539- See540- - https://github.com/encode/httpx/issues/2536541- - https://github.com/encode/httpx/issues/2721542- - https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode543- """544- return "&".join(545- [546- percent_encoded(k, safe="") + "=" + percent_encoded(v, safe="")547- for k, v in items548- ]549- )modified:httpx/_urls.py+17 added-10 removed
1 from __future__ import annotations2 3 import typing4-from urllib.parse import parse_qs, unquote4+from urllib.parse import parse_qs, unquote, urlencode5 6 import idna7 8 from ._types import QueryParamTypes9-from ._urlparse import urlencode, urlparse9+from ._urlparse import urlparse10 from ._utils import primitive_value_to_str11 12 __all__ = ["URL", "QueryParams"]13 14 15+# To urlencode query parameters, we use the whatwg query percent-encode set16+# and additionally escape U+0025 (%), U+0026 (&), U+002B (+) and U+003D (=).17+18+# https://url.spec.whatwg.org/#percent-encoded-bytes19+20+URLENCODE_SAFE = "".join(21+ [22+ chr(i)23+ for i in range(0x20, 0x7F)24+ if i not in (0x20, 0x22, 0x23, 0x25, 0x26, 0x2B, 0x3C, 0x3D, 0x3E)25+ ]26+)27+28+29 class URL:30 """31 url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")32 585 unmodified lines618 return False619 return sorted(self.multi_items()) == sorted(other.multi_items())620 621 def __str__(self) -> str:608- """609- Note that we use '%20' encoding for spaces, and treat '/' as a safe610- character.622+ return urlencode(self.multi_items(), safe=URLENCODE_SAFE)623 612- See https://github.com/encode/httpx/issues/2536 and613- https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode614- """615- return urlencode(self.multi_items())616-624 def __repr__(self) -> str:625 class_name = self.__class__.__name__626 query_string = str(self)627 return f"{class_name}({query_string!r})"12 unmodified linesmodified:tests/models/test_url.py+8 added-12 removed
139 unmodified lines140 assert url.fragment == fragment141 142 143 def test_url_query_encoding():144- """145- URL query parameters should use '%20' for encoding spaces,146- and should treat '/' as a safe character. This behaviour differs147- across clients, but we're matching browser behaviour here.148-149- See https://github.com/encode/httpx/issues/2536150- and https://github.com/encode/httpx/discussions/2460151- """144 url = httpx.URL("https://www.example.com/?a=b c&d=e/f")145 assert url.raw_path == b"/?a=b%20c&d=e/f"146 147+ url = httpx.URL("https://www.example.com/?a=b+c&d=e/f")148+ assert url.raw_path == b"/?a=b+c&d=e/f"149+150 url = httpx.URL("https://www.example.com/", params={"a": "b c", "d": "e/f"})156- assert url.raw_path == b"/?a=b%20c&d=e%2Ff"151+ assert url.raw_path == b"/?a=b+c&d=e/f"152 153 154 def test_url_params():155 url = httpx.URL("https://example.org:123/path/to/somewhere", params={"a": "123"})127 unmodified lines283 # Percent-encoding in `params={}` should match browser form behavior.284 285 286 def test_param_with_space():292- # Params passed as form key-value pairs should be escaped.287+ # Params passed as form key-value pairs should be form escaped,288+ # Including the special case of "+" for space seperators.289 url = httpx.URL("http://webservice", params={"u": "with spaces"})294- assert str(url) == "http://webservice?u=with%20spaces"290+ assert str(url) == "http://webservice?u=with+spaces"291 292 293 def test_param_requires_encoding():294 # Params passed as form key-value pairs should be escaped.13 unmodified lines308 # Params passed as form key-value pairs should always be escaped,309 # even if they include a valid escape sequence.310 # We want to match browser form behaviour here.311 url = httpx.URL("http://webservice", params={"u": "http://example.com?q=foo%2Fa"})316- assert str(url) == "http://webservice?u=http%3A%2F%2Fexample.com%3Fq%3Dfoo%252Fa"312+ assert str(url) == "http://webservice?u=http://example.com?q%3Dfoo%252Fa"313 314 315 # Tests for query parameter percent encoding.316 #547 unmodified lines