do not include content-length header in 304

This commit is contained in:
Raphael Deem 2018-02-02 15:02:30 -08:00
parent 8b920d9d56
commit b4d05ac68b
2 changed files with 18 additions and 9 deletions

View File

@ -72,7 +72,12 @@ STATUS_CODES = {
511: b'Network Authentication Required' 511: b'Network Authentication Required'
} }
EMPTY_STATUS_CODES = [204, 304] # These should all have no response body. The True/False indicates if they
# should also include the content-length header.
EMPTY_STATUS_CODES = {
204: True,
304: False
}
class BaseHTTPResponse: class BaseHTTPResponse:
@ -198,13 +203,17 @@ class HTTPResponse(BaseHTTPResponse):
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
body = b''
content_length = 0
if self.status not in EMPTY_STATUS_CODES:
body = self.body body = self.body
content_length = self.headers.get('Content-Length', len(self.body)) content_length = self.headers.get('Content-Length', len(self.body))
self.headers['Content-Length'] = content_length self.headers['Content-Length'] = content_length
if self.status in EMPTY_STATUS_CODES:
body = b''
content_length = 0
self.headers['Content-Length'] = content_length
if not EMPTY_STATUS_CODES.get(self.status):
del self.headers['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)

View File

@ -99,12 +99,12 @@ def test_no_content(json_app):
request, response = json_app.test_client.get('/no-content/unmodified') request, response = json_app.test_client.get('/no-content/unmodified')
assert response.status == 304 assert response.status == 304
assert response.text == '' assert response.text == ''
assert response.headers['Content-Length'] == '0' assert response.headers.get('Content-Length') == None
request, response = json_app.test_client.get('/unmodified') request, response = json_app.test_client.get('/unmodified')
assert response.status == 304 assert response.status == 304
assert response.text == '' assert response.text == ''
assert response.headers['Content-Length'] == '0' assert response.headers.get('Content-Length') == None
request, response = json_app.test_client.delete('/') request, response = json_app.test_client.delete('/')
assert response.status == 204 assert response.status == 204