Response model now handles the 204 no content

This commit is contained in:
Arnulfo Solis 2018-02-01 17:51:51 +01:00
parent 2135294e2e
commit 68fd1b66b5
3 changed files with 11 additions and 7 deletions

View File

@ -195,8 +195,12 @@ class HTTPResponse(BaseHTTPResponse):
timeout_header = b'' timeout_header = b''
if keep_alive and keep_alive_timeout is not None: if keep_alive and keep_alive_timeout is not None:
timeout_header = b'Keep-Alive: %d\r\n' % keep_alive_timeout 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( self.headers['Content-Type'] = self.headers.get(
'Content-Type', self.content_type) 'Content-Type', self.content_type)
@ -218,7 +222,7 @@ class HTTPResponse(BaseHTTPResponse):
b'keep-alive' if keep_alive else b'close', b'keep-alive' if keep_alive else b'close',
timeout_header, timeout_header,
headers, headers,
self.body self.body if self.status is not 204 else b''
) )
@property @property
@ -239,8 +243,7 @@ def json(body, status=200, headers=None,
:param headers: Custom Headers. :param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder. :param kwargs: Remaining arguments that are passed to the json encoder.
""" """
_body = dumps(body, **kwargs) if body else None return HTTPResponse(dumps(body, **kwargs), headers=headers,
return HTTPResponse(_body, headers=headers,
status=status, content_type=content_type) status=status, content_type=content_type)

View File

@ -104,6 +104,7 @@ def test_json():
assert results.get('test') == True assert results.get('test') == True
def test_empty_json(): def test_empty_json():
app = Sanic('test_json') app = Sanic('test_json')
@ -114,7 +115,7 @@ def test_empty_json():
request, response = app.test_client.get('/') request, response = app.test_client.get('/')
assert response.status == 200 assert response.status == 200
assert response.text == '' assert response.text == 'null'
def test_invalid_json(): def test_invalid_json():