2017-11-21 5 views
1

미래를 취소하기 전에 asyncio.ClientSession을 폐쇄하면이가 제대로 나는 기다리고 있어요 가장 빠른 응답을 저장하고 나머지는 <pre><code>done, pending = await asyncio.wait( futures, return_when=FIRST_COMPLETED) print(done.pop().result()) for future in pending: future.cancel() </code></pre> <p>이 미래의 각</p>를 취소됩니다 작업의 목록을

있다 나는 다른 선물을 취소하는 경우
session = asyncio.CreateSession() 
# some code to request 
# some code to process response 
await session.close() 

, 내가 경고

Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x10f95c6d8> 

가장 좋은 방법은 무엇인가를 얻을 작업을 취소하기 전에이 열린 세션을 닫으시겠습니까? 당신이 뭔가를 취소하려면

답변

1

1)

for future in pending: 
    future.cancel() 

cancel() 메소드를 호출 할뿐만 아니라 실제로 취소 작업을 기다리고 안 :

from contextlib import suppress 

for task in pending: 
    task.cancel() 
    with suppress(asyncio.CancelledError): 
     await task 

read this answer가 취소가 어떻게 작동하는지 볼하세요.

2)

session = asyncio.CreateSession() 
# some code to request 
# some code to process response 
await session.close() 

어딘가 CancelledError이 라인 (또는 다른 예외 사이)을 높일 수있다. 그럴 경우 await session.close() 행에 도달하지 않습니다. 모든 곳 파이썬에서 당신은 어떤 자원을 가지고/finally 블록 시도 해제/나중에 당신이 항상 복용 사이의 모든 코드를 포장해야을 확보 할 필요가있는 경우

: 다시

session = asyncio.CreateSession() 
try: 
    # some code to request 
    # some code to process response 
finally: 
    await session.close() 

, 그것은 not only 관련된 일반적인 패턴이다 asyncio.

+0

'with'구문이 나타났습니다. 당신의 설명은 기본적으로 '함께'하는 것입니다. 나 맞아? –

+0

@Abhinav_A 네, 그렇습니다. 현재 문법에서는 (와) 많은 경우에'with' 문법이 사용합니다. 새로운 async with 구문을 사용하는 것이 더 좋습니다 (예를 들어 첫 번째 코드 단편 [here] (https://stackoverflow.com/a/47172471/1113207) 참조). –