Skip to content
Myr

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

3 files+28 added−47 removed

modified:httpx/_urlparse.py+3 added-25 removed
95 unmodified lines
96 + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C)97 ]98)99100101# {scheme}: (optional)102# //{authority} (optional)103# {path}104# ?{query} (optional)
373 unmodified lines
478def PERCENT(string: str) -> str:479 return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")])480481481def percent_encoded(string: str, safe: str = "/") -> str:482def percent_encoded(string: str, safe: str) -> str:483 """484 Use percent-encoding to quote a string.485 """486 NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe
6 unmodified lines
493 [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string]494 )495496496def quote(string: str, safe: str = "/") -> str:497def quote(string: str, safe: str) -> str:498 """499 Use percent-encoding to quote a string, omitting existing '%xx' escape sequences.500501 See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1
22 unmodified lines
524 trailing_text = string[current_position:]525 parts.append(percent_encoded(trailing_text, safe=safe))526527 return "".join(parts)527528529def 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.533534 https://github.com/python/cpython/blob/b2f7b2ef0b5421e01efb8c7bee2ef95d3bab77eb/Lib/urllib/parse.py#L926535536 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.538539 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
1from __future__ import annotations23import typing4from urllib.parse import parse_qs, unquote4from urllib.parse import parse_qs, unquote, urlencode56import idna78from ._types import QueryParamTypes9from ._urlparse import urlencode, urlparse9from ._urlparse import urlparse10from ._utils import primitive_value_to_str1112__all__ = ["URL", "QueryParams"]131415# To urlencode query parameters, we use the whatwg query percent-encode set16# and additionally escape U+0025 (%), U+0026 (&), U+002B (+) and U+003D (=).1718# https://url.spec.whatwg.org/#percent-encoded-bytes1920URLENCODE_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)272829class URL:30 """31 url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")32
585 unmodified lines
618 return False619 return sorted(self.multi_items()) == sorted(other.multi_items())620621 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)623612 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())616624 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 lines
modified:tests/models/test_url.py+8 added-12 removed
139 unmodified lines
140 assert url.fragment == fragment141142143def 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.148149 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"146147 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"149150 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"152153154def test_url_params():155 url = httpx.URL("https://example.org:123/path/to/somewhere", params={"a": "123"})
127 unmodified lines
283# Percent-encoding in `params={}` should match browser form behavior.284285286def 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"291292293def test_param_requires_encoding():294 # Params passed as form key-value pairs should be escaped.
13 unmodified lines
308 # 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"313314315# Tests for query parameter percent encoding.316#
547 unmodified lines