Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use '%20' for encoding spaces in query parameters. #2543

Merged
merged 5 commits into from Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 8 additions & 1 deletion httpx/_urls.py
Expand Up @@ -616,7 +616,14 @@ def __eq__(self, other: typing.Any) -> bool:
return sorted(self.multi_items()) == sorted(other.multi_items())

def __str__(self) -> str:
return urlencode(self.multi_items())
"""
Note that we use '%20' encoding for spaces, and treat '/' as a safe
character.

See https://github.com/encode/httpx/issues/2536 and
https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode
"""
return urlencode(self.multi_items(), safe="/", quote_via=quote)

def __repr__(self) -> str:
class_name = self.__class__.__name__
Expand Down
16 changes: 16 additions & 0 deletions tests/models/test_url.py
Expand Up @@ -350,6 +350,22 @@ def test_url_with_empty_query():
assert url.raw_path == b"/path?"


def test_url_query_encoding():
"""
URL query parameters should use '%20' to encoding spaces,
and should treat '/' as a safe character. This behaviour differs
across clients, but we're matching browser behaviour here.

See https://github.com/encode/httpx/issues/2536
and https://github.com/encode/httpx/discussions/2460
"""
url = httpx.URL("https://www.example.com/?a=b c&d=e/f")
assert url.raw_path == b"/?a=b%20c&d=e/f"

url = httpx.URL("https://www.example.com/", params={"a": "b c", "d": "e/f"})
assert url.raw_path == b"/?a=b%20c&d=e/f"


def test_url_with_url_encoded_path():
url = httpx.URL("https://www.example.com/path%20to%20somewhere")
assert url.path == "/path to somewhere"
Expand Down