Skip to content

Commit

Permalink
Add option not to read body in Response.parse.
Browse files Browse the repository at this point in the history
This allows keeping the connection open after reading the response
to a CONNECT request.
  • Loading branch information
aaugustin committed Jan 31, 2025
1 parent 419227e commit 469c41a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/websockets/http11.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down
8 changes: 7 additions & 1 deletion tests/test_http11.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit 469c41a

Please sign in to comment.