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

Make content argument required to JSONResponse #1431

Merged
merged 17 commits into from
Jan 26, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
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
14 changes: 9 additions & 5 deletions starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,25 @@ class Response:
def __init__(
self,
content: typing.Any = None,
status_code: int = 200,
status_code: int = None,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None,
) -> None:
self.status_code = status_code
if media_type is not None:
self.media_type = media_type
self.background = background
self.body = self.render(content)

if content is None:
self.body = b""
self.status_code = status_code or 204
else:
self.body = self.render(content)
self.status_code = status_code or 200

self.init_headers(headers)

def render(self, content: typing.Any) -> bytes:
if content is None:
return b""
if isinstance(content, bytes):
return content
return content.encode(self.charset)
Expand Down
7 changes: 4 additions & 3 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ async def app(scope, receive, send):

def test_json_none_response(test_client_factory):
async def app(scope, receive, send):
response = JSONResponse(None)
response = JSONResponse()
await response(scope, receive, send)

client = test_client_factory(app)
response = client.get("/")
assert response.json() is None
assert response.content == b""


def test_redirect_response(test_client_factory):
Expand Down Expand Up @@ -330,7 +330,8 @@ def test_empty_response(test_client_factory):
app = Response()
client: TestClient = test_client_factory(app)
response = client.get("/")
assert response.headers["content-length"] == "0"
assert response.status_code == 204
assert "content-length" not in response.headers
aminalaee marked this conversation as resolved.
Show resolved Hide resolved


def test_empty_204_response(test_client_factory):
Expand Down