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

Enhance super_len to count encoded bytes for str #6589

Merged
merged 2 commits into from
Feb 23, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/requests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ def super_len(o):
total_length = None
current_position = 0

if isinstance(o, str):
sigmavirus24 marked this conversation as resolved.
Show resolved Hide resolved
o = o.encode("utf-8")

if hasattr(o, "__len__"):
total_length = len(o)

Expand Down
17 changes: 17 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1808,6 +1808,23 @@ def test_autoset_header_values_are_native(self, httpbin):

assert p.headers["Content-Length"] == length

def test_content_length_for_bytes_data(self, httpbin):
data = "This is a string containing multi-byte UTF-8 ☃️"
encoded_data = data.encode("utf-8")
length = str(len(encoded_data))
req = requests.Request("POST", httpbin("post"), data=encoded_data)
p = req.prepare()

assert p.headers["Content-Length"] == length

def test_content_length_for_string_data_counts_bytes(self, httpbin):
data = "This is a string containing multi-byte UTF-8 ☃️"
length = str(len(data.encode("utf-8")))
req = requests.Request("POST", httpbin("post"), data=data)
p = req.prepare()

assert p.headers["Content-Length"] == length

def test_nonhttp_schemes_dont_check_URLs(self):
test_urls = (
"data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",
Expand Down
Loading