]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
Add "Content-Length: 0" on POST, PUT, PATCH if required. (#995)
authorTom Christie <tom@tomchristie.com>
Tue, 26 May 2020 14:03:55 +0000 (15:03 +0100)
committerGitHub <noreply@github.com>
Tue, 26 May 2020 14:03:55 +0000 (15:03 +0100)
* 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>
httpx/_models.py
tests/client/test_client.py

index 865fd9a209dc1dcf9eb0cf3cabdd764b3d922a33..683dde16ed9f3312c9f0e0c95837bfcd6e5a4c09 100644 (file)
@@ -616,6 +616,9 @@ class Request:
         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
@@ -626,6 +629,8 @@ class Request:
             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:
index 1555690bbda2e18f43086dd803875bd741daa3ba..0bb1cc193fdded757ea47d5bdb4bc61312787555 100644 (file)
@@ -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!")