Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")))

Expand Down
18 changes: 18 additions & 0 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from typing import Callable

import anyio
import pytest
Expand Down Expand Up @@ -366,3 +367,20 @@ def test_streaming_response_known_size(test_client_factory):
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.headers["content-length"] == "10"


@pytest.mark.parametrize("status_code", (100, 204, 304))
def test_no_content_length(
status_code: int, test_client_factory: Callable[..., TestClient]
):
app = Response(content=b"non_empty", status_code=status_code)
client = test_client_factory(app)
response = client.get("/")
assert "content-length" not in response.headers


def test_json_response_no_content_length(test_client_factory):
app = JSONResponse("null", status_code=204)
client = test_client_factory(app)
response = client.get("/")
assert "content-length" not in response.headers