diff --git a/sanic/response.py b/sanic/response.py index 2402b432..7a490ffe 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -195,8 +195,12 @@ class HTTPResponse(BaseHTTPResponse): timeout_header = b'' if keep_alive and keep_alive_timeout is not None: timeout_header = b'Keep-Alive: %d\r\n' % keep_alive_timeout - self.headers['Content-Length'] = self.headers.get( - 'Content-Length', len(self.body)) + + content_length = 0 + if self.status is not 204: + content_length = self.headers.get('Content-Length', len(self.body)) + self.headers['Content-Length'] = content_length + self.headers['Content-Type'] = self.headers.get( 'Content-Type', self.content_type) @@ -218,7 +222,7 @@ class HTTPResponse(BaseHTTPResponse): b'keep-alive' if keep_alive else b'close', timeout_header, headers, - self.body + self.body if self.status is not 204 else b'' ) @property @@ -239,8 +243,7 @@ def json(body, status=200, headers=None, :param headers: Custom Headers. :param kwargs: Remaining arguments that are passed to the json encoder. """ - _body = dumps(body, **kwargs) if body else None - return HTTPResponse(_body, headers=headers, + return HTTPResponse(dumps(body, **kwargs), headers=headers, status=status, content_type=content_type) diff --git a/tests/test_requests.py b/tests/test_requests.py index 49e73a55..14da4b0b 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -104,6 +104,7 @@ def test_json(): assert results.get('test') == True + def test_empty_json(): app = Sanic('test_json') @@ -114,7 +115,7 @@ def test_empty_json(): request, response = app.test_client.get('/') assert response.status == 200 - assert response.text == '' + assert response.text == 'null' def test_invalid_json(): diff --git a/tests/test_response.py b/tests/test_response.py index 88bd8a3a..475da8b6 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -43,7 +43,7 @@ def test_method_not_allowed(): return response.json({'hello': 'world'}) request, response = app.test_client.head('/') - assert response.headers['Allow']== 'GET' + assert response.headers['Allow'] == 'GET' @app.post('/') async def test(request):