@@ -54,11 +54,12 @@ def __stream__(self) -> Iterator[_T]:
5454 process_data = self ._client ._process_response_data
5555 iterator = self ._iter_events ()
5656
57- for sse in iterator :
58- yield process_data (data = sse .json (), cast_to = cast_to , response = response )
59-
60- # As we might not fully consume the response stream, we need to close it explicitly
61- response .close ()
57+ try :
58+ for sse in iterator :
59+ yield process_data (data = sse .json (), cast_to = cast_to , response = response )
60+ finally :
61+ # Ensure the response is closed even if the consumer doesn't read all data
62+ response .close ()
6263
6364 def __enter__ (self ) -> Self :
6465 return self
@@ -117,11 +118,12 @@ async def __stream__(self) -> AsyncIterator[_T]:
117118 process_data = self ._client ._process_response_data
118119 iterator = self ._iter_events ()
119120
120- async for sse in iterator :
121- yield process_data (data = sse .json (), cast_to = cast_to , response = response )
122-
123- # As we might not fully consume the response stream, we need to close it explicitly
124- await response .aclose ()
121+ try :
122+ async for sse in iterator :
123+ yield process_data (data = sse .json (), cast_to = cast_to , response = response )
124+ finally :
125+ # Ensure the response is closed even if the consumer doesn't read all data
126+ await response .aclose ()
125127
126128 async def __aenter__ (self ) -> Self :
127129 return self
0 commit comments