Skip to content

Commit b8be93a

Browse files
authored
Merge pull request #6589 from bruceadams/super_len_str_utf-8
Enhance `super_len` to count encoded bytes for str
2 parents 3587a5f + 3fd309a commit b8be93a

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

src/requests/utils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,9 @@ def super_len(o):
134134
total_length = None
135135
current_position = 0
136136

137+
if isinstance(o, str):
138+
o = o.encode("utf-8")
139+
137140
if hasattr(o, "__len__"):
138141
total_length = len(o)
139142

tests/test_requests.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1808,6 +1808,23 @@ def test_autoset_header_values_are_native(self, httpbin):
18081808

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

1811+
def test_content_length_for_bytes_data(self, httpbin):
1812+
data = "This is a string containing multi-byte UTF-8 ☃️"
1813+
encoded_data = data.encode("utf-8")
1814+
length = str(len(encoded_data))
1815+
req = requests.Request("POST", httpbin("post"), data=encoded_data)
1816+
p = req.prepare()
1817+
1818+
assert p.headers["Content-Length"] == length
1819+
1820+
def test_content_length_for_string_data_counts_bytes(self, httpbin):
1821+
data = "This is a string containing multi-byte UTF-8 ☃️"
1822+
length = str(len(data.encode("utf-8")))
1823+
req = requests.Request("POST", httpbin("post"), data=data)
1824+
p = req.prepare()
1825+
1826+
assert p.headers["Content-Length"] == length
1827+
18111828
def test_nonhttp_schemes_dont_check_URLs(self):
18121829
test_urls = (
18131830
"data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",

0 commit comments

Comments
 (0)