]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Don't set headers for responses with 1xx, 204 and 304 status code (#1397)
authorMarcelo Trylesinski <marcelotryle@gmail.com>
Mon, 10 Jan 2022 11:08:31 +0000 (12:08 +0100)
committerGitHub <noreply@github.com>
Mon, 10 Jan 2022 11:08:31 +0000 (12:08 +0100)
* Don't set  headers for responses with 1xx, 204 and 304 status code

* Fix test

Co-authored-by: Tom Christie <tom@tomchristie.com>
starlette/responses.py
tests/test_responses.py

index da765cfa9a78df923fa1225f5b2a663512302340..26d730540cd90f4ba959d7ea19df5796ee92fe18 100644 (file)
@@ -71,7 +71,11 @@ class Response:
             populate_content_type = b"content-type" not in keys
 
         body = getattr(self, "body", None)
-        if body is not None and populate_content_length:
+        if (
+            body is not None
+            and populate_content_length
+            and not (self.status_code < 200 or self.status_code in (204, 304))
+        ):
             content_length = str(len(body))
             raw_headers.append((b"content-length", content_length.encode("latin-1")))
 
index 150fe47952101e10eff7670e7668bd3a3365c15e..e2337bdca1175814a97ef4c0d6a5b70b2f940d0c 100644 (file)
@@ -333,6 +333,13 @@ def test_empty_response(test_client_factory):
     assert response.headers["content-length"] == "0"
 
 
+def test_empty_204_response(test_client_factory):
+    app = Response(status_code=204)
+    client: TestClient = test_client_factory(app)
+    response = client.get("/")
+    assert "content-length" not in response.headers
+
+
 def test_non_empty_response(test_client_factory):
     app = Response(content="hi")
     client: TestClient = test_client_factory(app)