diff --git a/aiohttp/web_reqrep.py b/aiohttp/web_reqrep.py index 68ab7fdf5f2..5022ac6b140 100644 --- a/aiohttp/web_reqrep.py +++ b/aiohttp/web_reqrep.py @@ -852,11 +852,15 @@ def text(self, text): self.body = text.encode(self.charset) + def should_send_body(self): + return (self._req.method != hdrs.METH_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 ceb240b24cf..3ed8adb920b 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