Allow empty body without Content-Type; Introduce response.empty() (#1736)

This commit is contained in:
Liran Nuna 2019-12-23 12:16:53 -08:00 committed by Stephen Sadowski
parent 3f6a978328
commit fccbc1adc4
2 changed files with 27 additions and 4 deletions

View File

@ -153,7 +153,7 @@ class HTTPResponse(BaseHTTPResponse):
body=None, body=None,
status=200, status=200,
headers=None, headers=None,
content_type="text/plain", content_type=None,
body_bytes=b"", body_bytes=b"",
): ):
self.content_type = content_type self.content_type = content_type
@ -181,9 +181,9 @@ class HTTPResponse(BaseHTTPResponse):
"Content-Length", len(self.body) "Content-Length", len(self.body)
) )
self.headers["Content-Type"] = self.headers.get( # self.headers get priority over content_type
"Content-Type", self.content_type if self.content_type and "Content-Type" not in self.headers:
) self.headers["Content-Type"] = self.content_type
if self.status in (304, 412): if self.status in (304, 412):
self.headers = remove_entity_headers(self.headers) self.headers = remove_entity_headers(self.headers)
@ -214,6 +214,18 @@ class HTTPResponse(BaseHTTPResponse):
return self._cookies return self._cookies
def empty(
status=204, headers=None,
):
"""
Returns an empty response to the client.
:param status Response code.
:param headers Custom Headers.
"""
return HTTPResponse(body_bytes=b"", status=status, headers=headers,)
def json( def json(
body, body,
status=200, status=200,

View File

@ -21,6 +21,7 @@ from sanic.response import (
raw, raw,
stream, stream,
) )
from sanic.response import empty
from sanic.server import HttpProtocol from sanic.server import HttpProtocol
from sanic.testing import HOST, PORT from sanic.testing import HOST, PORT
@ -591,3 +592,13 @@ def test_raw_response(app):
request, response = app.test_client.get("/test") request, response = app.test_client.get("/test")
assert response.content_type == "application/octet-stream" assert response.content_type == "application/octet-stream"
assert response.body == b"raw_response" assert response.body == b"raw_response"
def test_empty_response(app):
@app.get("/test")
def handler(request):
return empty()
request, response = app.test_client.get("/test")
assert response.content_type is None
assert response.body == b""