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

Optimize _encode_invalid_chars #1787

Merged
merged 1 commit into from Jan 21, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions CHANGES.rst
Expand Up @@ -6,6 +6,8 @@ dev

* Drop support for EOL Python 3.4 (Pull #1774)

* Optimize _encode_invalid_chars (Pull #1787)


1.25.7 (2019-11-11)
-------------------
Expand Down
15 changes: 6 additions & 9 deletions src/urllib3/util/url.py
Expand Up @@ -216,18 +216,15 @@ def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"):

component = six.ensure_text(component)

# Normalize existing percent-encoded bytes.
# Try to see if the component we're encoding is already percent-encoded
# so we can skip all '%' characters but still encode all others.
percent_encodings = PERCENT_RE.findall(component)

# Normalize existing percent-encoded bytes.
for enc in percent_encodings:
if not enc.isupper():
component = component.replace(enc, enc.upper())
component, percent_encodings = PERCENT_RE.subn(
lambda match: match.group(0).upper(), component
)

uri_bytes = component.encode("utf-8", "surrogatepass")
is_percent_encoded = len(percent_encodings) == uri_bytes.count(b"%")

is_percent_encoded = percent_encodings == uri_bytes.count(b"%")
encoded_component = bytearray()

for i in range(0, len(uri_bytes)):
Expand All @@ -237,7 +234,7 @@ def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"):
if (is_percent_encoded and byte == b"%") or (
byte_ord < 128 and byte.decode() in allowed_chars
):
encoded_component.extend(byte)
encoded_component += byte
continue
encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper()))

Expand Down