File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11from __future__ import annotations
22
33from collections .abc import Awaitable , Collection , Mapping
4+ from contextlib import aclosing , closing
45from functools import wraps
56from inspect import isasyncgen , isgenerator
67from typing import Any , Callable , ParamSpec , Union
@@ -74,15 +75,19 @@ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> DatastarResponse | None:
7475 if isasyncgen (r ):
7576 request = args [0 ]
7677 response = await request .respond (response = DatastarResponse ())
77- async for event in r :
78- await response .send (event )
78+ # Make sure when the client cancels the stream clean up the generator now
79+ # Without the aclosing manager it would happen at garbage collection
80+ async with aclosing (r ) as ait :
81+ async for event in ait :
82+ await response .send (event )
7983 await response .eof ()
8084 return None
8185 if isgenerator (r ):
8286 request = args [0 ]
8387 response = await request .respond (response = DatastarResponse ())
84- for event in r :
85- await response .send (event )
88+ with closing (r ) as it :
89+ for event in it :
90+ await response .send (event )
8691 await response .eof ()
8792 return None
8893 return DatastarResponse (r )
You can’t perform that action at this time.
0 commit comments