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''
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)

View File

@ -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():

View File

@ -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):