Skip to content

Commit

Permalink
Add "Content-Length: 0" on POST, PUT, PATCH if required. (#995)
Browse files Browse the repository at this point in the history
* Add Content-Length: 0 on POST, PUT, PATCH if required.

* Update tests/client/test_client.py

Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
  • Loading branch information
tomchristie and florimondmanca committed May 26, 2020
1 parent 66a4537 commit 7c8158a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions httpx/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,9 @@ def prepare(self) -> None:
auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []

has_host = "host" in self.headers
has_content_length = (
"content-length" in self.headers or "transfer-encoding" in self.headers
)
has_user_agent = "user-agent" in self.headers
has_accept = "accept" in self.headers
has_accept_encoding = "accept-encoding" in self.headers
Expand All @@ -626,6 +629,8 @@ def prepare(self) -> None:
if url.userinfo:
url = url.copy_with(username=None, password=None)
auto_headers.append((b"host", url.authority.encode("ascii")))
if not has_content_length and self.method in ("POST", "PUT", "PATCH"):
auto_headers.append((b"content-length", b"0"))
if not has_user_agent:
auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))
if not has_accept:
Expand Down
16 changes: 16 additions & 0 deletions tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ def test_build_request(server):
assert response.json()["Custom-header"] == "value"


def test_build_post_request(server):
url = server.url.copy_with(path="/echo_headers")
headers = {"Custom-header": "value"}

with httpx.Client() as client:
request = client.build_request("POST", url)
request.headers.update(headers)
response = client.send(request)

assert response.status_code == 200
assert response.url == url

assert response.json()["Content-length"] == "0"
assert response.json()["Custom-header"] == "value"


def test_post(server):
with httpx.Client() as client:
response = client.post(server.url, data=b"Hello, world!")
Expand Down

0 comments on commit 7c8158a

Please sign in to comment.