Catch asyncio.CancelledError and raise GeneratorExit in aiter functions
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Idoneità per principianti
- 65/100
Direzione di ricerca
Inizia in httpx/_client.py leggendo le funzioni aiter_raw e aiter_bytes e il modo in cui i relativi stream asincroni vengono chiusi. Riproduci l'annullamento con generator.close() o asyncio.gather(..., return_exceptions=True), quindi verifica che l'annullamento produca GeneratorExit mentre la pulizia della response avviene comunque.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Originally opened by
@gjmhmm8on 2023-11-24 18:32:59 in encode/httpx
Hello, I am using httpx to make asynchronous requests in a generator function. However, I encountered a problem when I tried to cancel the generator using generator.close() or asyncio.gather(*tasks, return_exceptions=True). The generator did not exit gracefully and raised an asyncio.CancelledError instead of a GeneratorExit. This caused some unwanted side effects and made it difficult to handle the cancellation properly.
I looked into the source code of httpx and found that the problem was in the aiter_raw and aiter_bytes functions in the httpx/_client.py module. These functions use async for to iterate over the response stream, but they do not catch the asyncio.CancelledError that may be raised when the stream is cancelled. According to the [documentation] of asyncio.CancelledError, this exception should be caught and either re-raised or suppressed. In this case, I think it would make sense to re-raise it as a GeneratorExit, which is the expected exception for generator termination.
I suggest adding a try-except block around the async for loop in the aiter_raw and aiter_bytes functions, like this:
async def aiter_raw(
self, chunk_size: typing.Optional[int] = None
) -> typing.AsyncIterator[bytes]:
"""
A byte-iterator over the raw response content.
"""
if self.is_stream_consumed:
raise StreamConsumed()
if self.is_closed:
raise StreamClosed()
if not isinstance(self.stream, AsyncByteStream):
raise RuntimeError("Attempted to call an async iterator on an sync stream.")
self.is_stream_consumed = True
self._num_bytes_downloaded = 0
chunker = ByteChunker(chunk_size=chunk_size)
try:
with request_context(request=self._request):
async for raw_stream_bytes in self.stream:
self._num_bytes_downloaded += len(raw_stream_bytes)
for chunk in chunker.decode(raw_stream_bytes):
await asyncio.sleep(0)
yield chunk
for chunk in chunker.flush():
await asyncio.sleep(0)
yield chunk
except asyncio.CancelledError:
raise GeneratorExit
finally:
await self.aclose()
- Lingua principale
- Python
- Stelle
- 1.6k
- Fork
- 103
- Merge medio
- 1g 19h
- PR unite (30g)
- 25
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di pydantic/httpx2
-
Please revert aiter_bytes signature to AsyncIteratorForse di nuovo libera Una pull request per questa issue è stata chiusa senza essere unita. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
pydantic/httpx2#1158 · 2 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
Export AutoBackendForse di nuovo libera Una pull request per questa issue è stata chiusa senza essere unita. Aperta
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 92/100
pydantic/httpx2#1131 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 65/100
I maintainer di solito rispondono entro 1 giorno
-
Mention header name error message for invalid header encodingsForse di nuovo libera Una pull request per questa issue è stata chiusa senza essere unita. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
pydantic/httpx2#864 · 3 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
Support DigestAuth with "x-www-authenticate" in first response headerForse già presa Una pull request collegata a questa issue è aperta o già unita. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di pydantic/httpx2
Issue simili
-
Email validation accepts a trailing newlineForse già presa @marcello-pichini l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 1 giorno
-
Contributing instructionsAperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
dbt-labs/spark-utils#51 ·
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 85/100
I maintainer di solito rispondono entro 1 giorno
-
bug frontend
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
vendrabuck/HERD#1419 ·
I maintainer di solito rispondono entro 1 giorno