Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Raise RuntimeError if transport is None
When a client disconnects immediately after connecting, the transport
might become None. This should not lead to an assertion, since this can
happen in real-world scenarios. Use a RuntimeException instead.
  • Loading branch information
agners committed Nov 13, 2025
commit 9f20389bb652daca3925e0e67cf42e3708e1680d
3 changes: 2 additions & 1 deletion aiohttp/web_fileresponse.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ async def _sendfile(

loop = request._loop
transport = request.transport
assert transport is not None
if transport is None:
raise RuntimeError("Transport is not available")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this should be a RuntimeError. It's probably a ConnectionError or its subclass.

We should also ensure that it doesn't leak to the end-users and gets converted to some kind of a ClientError if they use high-level interfaces.
In fact, we already have things like ClientConnectionResetError in the hierarchy: https://docs.aiohttp.org/en/stable/client_reference.html#hierarchy-of-exceptions.

Or we could be raising BrokenPipeError / ConnectionResetError (subclasses of ConnectionError) directly.

Note that the docs aready suggest handling OSError (base of ConnectionError) when performing I/O on the server side: https://docs.aiohttp.org/en/stable/web_advanced.html#peer-disconnection. So raising ConnectionError-derived exceptions would be in line with that.


try:
await loop.sendfile(transport, fobj, offset, count)
Expand Down
3 changes: 2 additions & 1 deletion aiohttp/web_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,8 @@ def _pre_start(self, request: BaseRequest) -> tuple[str | None, WebSocketWriter]
self.force_close()
self._compress = compress
transport = request._protocol.transport
assert transport is not None
if transport is None:
raise RuntimeError("Transport is not available")
writer = WebSocketWriter(
request._protocol,
transport,
Expand Down
9 changes: 9 additions & 0 deletions tests/test_web_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,3 +671,12 @@ async def test_get_extra_info(
ws._writer = ws_transport

assert expected_result == ws.get_extra_info(valid_key, default_value)


async def test_prepare_transport_not_available(make_request: _RequestMaker) -> None:
req = make_request("GET", "/")
ws = web.WebSocketResponse()
# Simulate transport being None
req._protocol.transport = None
with pytest.raises(RuntimeError, match="Transport is not available"):
await ws.prepare(req)
Loading