From 7b309afb7d52914df23f994c4911b4199e4bade2 Mon Sep 17 00:00:00 2001 From: Dennis Brakhane Date: Wed, 20 Oct 2021 16:49:42 +0200 Subject: [PATCH] Ignore BrokenResourceError in BaseHTTPMiddleware ASGI specifies that send is a no-op when the connection is closed. HTTPMiddleware uses anyio streams which will raise an exception when the connection is closed prematurely. So we need to ignore the exception in our send function. Fixes #1284 --- starlette/middleware/base.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/starlette/middleware/base.py b/starlette/middleware/base.py index 77ba669251..f23e2b7608 100644 --- a/starlette/middleware/base.py +++ b/starlette/middleware/base.py @@ -1,4 +1,5 @@ import typing +from contextlib import suppress import anyio @@ -25,9 +26,13 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: async def call_next(request: Request) -> Response: send_stream, recv_stream = anyio.create_memory_object_stream() + async def docile_stream_send(data): + with suppress(anyio.BrokenResourceError): + await send_stream.send(data) + async def coro() -> None: async with send_stream: - await self.app(scope, request.receive, send_stream.send) + await self.app(scope, request.receive, docile_stream_send) task_group.start_soon(coro)