Drop body from responses on HEAD requests (#317)

* Drop body from responses on HEAD requests

* Linting

* Endpoints supporting HEAD should automatically support GET
This commit is contained in:
Tom Christie 2019-01-14 11:07:23 +00:00 committed by GitHub
parent a59b5295ef
commit 93a124805f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 2 deletions

View File

@ -162,7 +162,13 @@ class Route(BaseRoute):
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
self.methods = methods
if methods is None:
self.methods = None
else:
self.methods = set([method.upper() for method in methods])
if "GET" in self.methods:
self.methods |= set(["HEAD"])
self.path_regex, self.path_format, self.param_convertors = self.compile_path(
path
)

View File

@ -173,7 +173,8 @@ class _ASGIAdapter(requests.adapters.HTTPAdapter):
), 'Received "http.response.body" after response completed.'
body = message.get("body", b"")
more_body = message.get("more_body", False)
raw_kwargs["body"].write(body)
if request.method != "HEAD":
raw_kwargs["body"].write(body)
if not more_body:
raw_kwargs["body"].seek(0)
response_complete = True

View File

@ -100,6 +100,10 @@ def test_func_route():
assert response.status_code == 200
assert response.text == "Hello, world!"
response = client.head("/func")
assert response.status_code == 200
assert response.text == ""
def test_async_route():
response = client.get("/async")

View File

@ -287,3 +287,16 @@ def test_populate_headers():
assert response.text == "hi"
assert response.headers["content-length"] == "2"
assert response.headers["content-type"] == "text/html; charset=utf-8"
def test_head_method():
def app(scope):
async def asgi(receive, send):
response = Response("hello, world", media_type="text/plain")
await response(receive, send)
return asgi
client = TestClient(app)
response = client.head("/")
assert response.text == ""