Skip to content
Myr

Merge pull request #3545 from nateprewitt/new_prepare_content_length

Before adoption: this commit came in with the history the project adopted, so no landing records it.

removing redundant logic from prepare_content_length

authored by Ian Cordasco · committed by GitHub · parents ddf7df9, 31b35ab · Browse files · 2 files+20 added−12 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+20 added−12 removed

  • tests:+10 added−0 removed
  • other:+10 added−12 removed

2 files+20 added−12 removed

modified:requests/models.py+10 added-12 removed
422 unmodified lines
423424 # Nottin' on you.425 body = None426 content_type = None427 length = None427428 if not data and json is not None:429 # urllib3 requires a bytes-like body. Python 2's json.dumps430 # provides this natively, but Python 3 gives a Unicode string.
42 unmodified lines
473474 self.body = body475476 def prepare_content_length(self, body):478 if hasattr(body, 'seek') and hasattr(body, 'tell'):479 curr_pos = body.tell()480 body.seek(0, 2)481 end_pos = body.tell()482 self.headers['Content-Length'] = builtin_str(max(0, end_pos - curr_pos))483 body.seek(curr_pos, 0)484 elif body is not None:485 l = super_len(body)486 if l:487 self.headers['Content-Length'] = builtin_str(l)488 elif (self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None):477 """Prepare Content-Length header based on request method and body"""478 if body is not None:479 length = super_len(body)480 if length:481 # If length exists, set it. Otherwise, we fallback482 # to Transfer-Encoding: chunked.483 self.headers['Content-Length'] = builtin_str(length)484 elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:485 # Set Content-Length to 0 for methods that can have a body486 # but don't provide one. (i.e. not GET or HEAD)487 self.headers['Content-Length'] = '0'488489 def prepare_auth(self, auth, url=''):490 """Prepares the given HTTP auth data."""
395 unmodified lines
modified:tests/test_requests.py+10 added
88 unmodified lines
89 def test_no_content_length(self, httpbin, method):90 req = requests.Request(method, httpbin(method.lower())).prepare()91 assert 'Content-Length' not in req.headers9293 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))94 def test_no_body_content_length(self, httpbin, method):95 req = requests.Request(method, httpbin(method.lower())).prepare()96 assert req.headers['Content-Length'] == '0'9798 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))99 def test_empty_content_length(self, httpbin, method):100 req = requests.Request(method, httpbin(method.lower()), data='').prepare()101 assert req.headers['Content-Length'] == '0'102103 def test_override_content_length(self, httpbin):104 headers = {105 'Content-Length': 'not zero'106 }
1740 unmodified lines