Allow empty body without Content-Type; Introduce response.empty() (#1736)
This commit is contained in:
parent
3f6a978328
commit
fccbc1adc4
|
@ -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,
|
||||
|
|
|
@ -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""
|
||||
|
|
Loading…
Reference in New Issue
Block a user