diff --git a/starlette/responses.py b/starlette/responses.py index da765cfa9..26d730540 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -71,7 +71,11 @@ def init_headers(self, headers: typing.Mapping[str, str] = None) -> None: 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"))) diff --git a/tests/test_responses.py b/tests/test_responses.py index 150fe4795..e2337bdca 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -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)