From: Mantas Date: Mon, 17 Jun 2019 14:20:08 +0000 (+0300) Subject: Allow None fore JSONResponse X-Git-Tag: 0.12.2~10^2 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=refs%2Fpull%2F556%2Fhead;p=thirdparty%2Fstarlette.git Allow None fore JSONResponse Previously `JSONResponse(None)` rendered empty string, but it should be 'null' instead. This change fixes it. --- diff --git a/starlette/responses.py b/starlette/responses.py index 48afc47a..13982db5 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -39,10 +39,7 @@ class Response: media_type: str = None, background: BackgroundTask = None, ) -> None: - if content is None: - self.body = b"" - else: - self.body = self.render(content) + self.body = self.render(content) self.status_code = status_code if media_type is not None: self.media_type = media_type @@ -50,6 +47,8 @@ class Response: 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) diff --git a/tests/test_responses.py b/tests/test_responses.py index 3d5de413..c7ca0ac0 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -12,6 +12,7 @@ from starlette.responses import ( Response, StreamingResponse, UJSONResponse, + JSONResponse, ) from starlette.testclient import TestClient @@ -46,6 +47,16 @@ def test_ujson_response(): assert response.json() == {"hello": "world"} +def test_json_none_response(): + async def app(scope, receive, send): + response = JSONResponse(None) + await response(scope, receive, send) + + client = TestClient(app) + response = client.get("/") + assert response.json() is None + + def test_redirect_response(): async def app(scope, receive, send): if scope["path"] == "/":