From 4a5347f6159aa9079f262ec2fddd2b5d57f58cad Mon Sep 17 00:00:00 2001 From: Lubomir Gelo Date: Mon, 21 Mar 2016 21:40:14 +0100 Subject: [PATCH 1/2] Don't send body in response to HEAD request --- aiohttp/web_reqrep.py | 6 +++++- tests/test_web_functional.py | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/aiohttp/web_reqrep.py b/aiohttp/web_reqrep.py index f47fa32ee4c..bfc268e7a39 100644 --- a/aiohttp/web_reqrep.py +++ b/aiohttp/web_reqrep.py @@ -851,11 +851,15 @@ def text(self, text): self.body = text.encode(self.charset) + def should_send_body(self): + return (self._req.method.lower() != 'head' and + self._status not in [204, 304]) + @asyncio.coroutine def write_eof(self): try: body = self._body - if body is not None: + if body is not None and self.should_send_body(): self.write(body) finally: self.set_tcp_nodelay(True) diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py index 16654347df5..0c7b279b167 100644 --- a/tests/test_web_functional.py +++ b/tests/test_web_functional.py @@ -98,6 +98,32 @@ def go(): self.loop.run_until_complete(go()) logger.exception.assert_called_with("Error handling request") + def test_head_returns_empty_body(self): + + @asyncio.coroutine + def handler(request): + body = yield from request.read() + self.assertEqual(b'', body) + return web.Response(body=b'test') + + @asyncio.coroutine + def go(): + _, _, url = yield from self.create_server('HEAD', '/', handler) + with ClientSession(loop=self.loop) as session: + resp = yield from session.head(url, version=HttpVersion11) + self.assertEqual(200, resp.status) + txt = yield from resp.text() + self.assertEqual('', txt) + resp.close() + + resp = yield from session.head(url, version=HttpVersion11) + self.assertEqual(200, resp.status) + txt = yield from resp.text() + self.assertEqual('', txt) + resp.close() + + self.loop.run_until_complete(go()) + def test_post_form(self): @asyncio.coroutine From a7d5995b67f9f0c131db980b682671bc0aaa922d Mon Sep 17 00:00:00 2001 From: Lubomir Gelo Date: Tue, 22 Mar 2016 09:49:27 +0100 Subject: [PATCH 2/2] Use hdrs.METH_HEAD instead of 'head' --- aiohttp/web_reqrep.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aiohttp/web_reqrep.py b/aiohttp/web_reqrep.py index bfc268e7a39..04580f47633 100644 --- a/aiohttp/web_reqrep.py +++ b/aiohttp/web_reqrep.py @@ -852,7 +852,7 @@ def text(self, text): self.body = text.encode(self.charset) def should_send_body(self): - return (self._req.method.lower() != 'head' and + return (self._req.method != hdrs.METH_HEAD and self._status not in [204, 304]) @asyncio.coroutine