From c470d8beca0a7a789321eee03e52613922aa70ba Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Fri, 31 Jan 2025 22:16:21 +0100 Subject: [PATCH] Add option not to read body in Response.parse. This allows keeping the connection open after reading the response to a CONNECT request. --- src/websockets/http11.py | 10 +++++++--- tests/test_http11.py | 8 +++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/websockets/http11.py b/src/websockets/http11.py index 49d7b9a4..530ac3d0 100644 --- a/src/websockets/http11.py +++ b/src/websockets/http11.py @@ -210,6 +210,7 @@ def parse( read_line: Callable[[int], Generator[None, None, bytes]], read_exact: Callable[[int], Generator[None, None, bytes]], read_to_eof: Callable[[int], Generator[None, None, bytes]], + include_body: bool = True, ) -> Generator[None, None, Response]: """ Parse a WebSocket handshake response. @@ -265,9 +266,12 @@ def parse( headers = yield from parse_headers(read_line) - body = yield from read_body( - status_code, headers, read_line, read_exact, read_to_eof - ) + if include_body: + body = yield from read_body( + status_code, headers, read_line, read_exact, read_to_eof + ) + else: + body = b"" return cls(status_code, reason, headers, body) diff --git a/tests/test_http11.py b/tests/test_http11.py index bb0d27b9..3afb6d02 100644 --- a/tests/test_http11.py +++ b/tests/test_http11.py @@ -130,11 +130,12 @@ def setUp(self): super().setUp() self.reader = StreamReader() - def parse(self): + def parse(self, **kwargs): return Response.parse( self.reader.read_line, self.reader.read_exact, self.reader.read_to_eof, + **kwargs, ) def test_parse(self): @@ -322,6 +323,11 @@ def test_parse_body_not_modified(self): response = self.assertGeneratorReturns(self.parse()) self.assertEqual(response.body, b"") + def test_parse_without_body(self): + self.reader.feed_data(b"HTTP/1.1 200 Connection Established\r\n\r\n") + response = self.assertGeneratorReturns(self.parse(include_body=False)) + self.assertEqual(response.body, b"") + def test_serialize(self): # Example from the protocol overview in RFC 6455 response = Response(