From fccbc1adc492e8f805840dd20d7c6391ed49c00f Mon Sep 17 00:00:00 2001 From: Liran Nuna Date: Mon, 23 Dec 2019 12:16:53 -0800 Subject: [PATCH] Allow empty body without Content-Type; Introduce response.empty() (#1736) --- sanic/response.py | 20 ++++++++++++++++---- tests/test_response.py | 11 +++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/sanic/response.py b/sanic/response.py index 91fb25f4..c75af62e 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -153,7 +153,7 @@ class HTTPResponse(BaseHTTPResponse): body=None, status=200, headers=None, - content_type="text/plain", + content_type=None, body_bytes=b"", ): self.content_type = content_type @@ -181,9 +181,9 @@ class HTTPResponse(BaseHTTPResponse): "Content-Length", len(self.body) ) - self.headers["Content-Type"] = self.headers.get( - "Content-Type", self.content_type - ) + # self.headers get priority over 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): self.headers = remove_entity_headers(self.headers) @@ -214,6 +214,18 @@ class HTTPResponse(BaseHTTPResponse): 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( body, status=200, diff --git a/tests/test_response.py b/tests/test_response.py index 8feadb06..87bda1bf 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -21,6 +21,7 @@ from sanic.response import ( raw, stream, ) +from sanic.response import empty from sanic.server import HttpProtocol from sanic.testing import HOST, PORT @@ -591,3 +592,13 @@ def test_raw_response(app): request, response = app.test_client.get("/test") assert response.content_type == "application/octet-stream" 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""