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

Add check_ascii_printable function to reduce duplicated code #3281

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 13 additions & 17 deletions httpx/_urlparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,17 @@ def __str__(self) -> str:
)


def _check_ascii_printable(url: str, key: str | None = None) -> None:
for idx, char in enumerate(url):
if char.isascii() and not char.isprintable():
error = "Invalid non-printable ASCII character in URL"
if key is None:
error += f", {char!r} at position {idx}."
else:
error += f" {key} component, {char!r} at position {idx}."
raise InvalidURL(error)


def urlparse(url: str = "", **kwargs: str | None) -> ParseResult:
# Initial basic checks on allowable URLs.
# ---------------------------------------
Expand All @@ -159,13 +170,7 @@ def urlparse(url: str = "", **kwargs: str | None) -> ParseResult:

# If a URL includes any ASCII control characters including \t, \r, \n,
# then treat it as invalid.
if any(char.isascii() and not char.isprintable() for char in url):
char = next(char for char in url if char.isascii() and not char.isprintable())
idx = url.find(char)
error = (
f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}."
)
raise InvalidURL(error)
_check_ascii_printable(url)

# Some keyword arguments require special handling.
# ------------------------------------------------
Expand Down Expand Up @@ -209,16 +214,7 @@ def urlparse(url: str = "", **kwargs: str | None) -> ParseResult:

# If a component includes any ASCII control characters including \t, \r, \n,
# then treat it as invalid.
if any(char.isascii() and not char.isprintable() for char in value):
char = next(
char for char in value if char.isascii() and not char.isprintable()
)
idx = value.find(char)
error = (
f"Invalid non-printable ASCII character in URL {key} component, "
f"{char!r} at position {idx}."
)
raise InvalidURL(error)
_check_ascii_printable(value, key)

# Ensure that keyword arguments match as a valid regex.
if not COMPONENT_REGEX[key].fullmatch(value):
Expand Down
2 changes: 1 addition & 1 deletion scripts/lint
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ export SOURCE_FILES="httpx tests"

set -x

${PREFIX}ruff --fix $SOURCE_FILES
${PREFIX}ruff check --fix $SOURCE_FILES
${PREFIX}ruff format $SOURCE_FILES