Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't set headers for responses with 1xx, 204 and 304 status code #1397

Merged
merged 4 commits into from Jan 10, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion starlette/responses.py
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
7 changes: 7 additions & 0 deletions tests/test_responses.py
Expand Up @@ -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)
Expand Down